2013-03-13 64 views
0

我读数据,象这样一个循环:某些柜台更改列值的值

for(i in 1:2) 
{ 
n= paste(i,".txt", sep="") 
a<- sprintf("table%d", i, i) 
data <- read.table(toString(n), header = TRUE, sep = "\t") 
...... 

然后,我在做数据一堆东西(获得修剪方式和这样的),然后喂到包含每个文件的平均值的主表格中。我会在后面的方法上做方差分析。

无论如何,我需要对某些文件(或者语句中的那些文件)的分数进行反转,以使它们等价(a和b和a)。这是我如何去做的,但它看起来很愚蠢,有没有更好的语法来做到这一点?

if (i ==(2|4|6|7|9|11|14|16|18|19|21|23|25|28|30|32|34|36)) 
{ 
data$Reqresponse[data$Reqresponse == "a"] <- "nw" 
data$Reqresponse[data$Reqresponse == "b"] <- "w" 
data$Reqresponse[data$Reqresponse == "nw"] <- "b" 
data$Reqresponse[data$Reqresponse == "w"] <- "a" 
} 

感谢

+4

我不确定你的代码是否符合你的想法。我猜你只想运行符合你列出的数字的i值的if语句? – Dason 2013-03-13 05:31:47

+3

你是否想要%c中的'i%'(2,4,6,7,9,11,14,16,18,19,21,23,25,28,30,32,34,36)' ? – 2013-03-13 05:38:17

+0

@Dason:http://www.youtube.com/watch?v=1-b7RmmMJeo – 2013-03-13 05:38:41

回答

3

,如果你想换的东西出来,你需要把它们暂时某处。

如果你这样做a <- b然后b <- a它们都会以相同的值结束。 你需要做的,而不是TMP <- aa <- bb <- TMP

对于or语句,你可能寻找%in%为@塞巴斯蒂安-C指出。

1

你在做什么就是我在发现plyr之前是如何接近事物的。以下是我现在如何处理类似的情况。有可能有人能够更快地向你展示,但这里是我将如何处理你的情况。

library(plyr) 

#Assuming all your files are in the working directory 
filenames <- list.files(".", ".txt") 
#Assuming your files are "1.txt" etc 
file.index <- sub("([0-9]+).txt", "\\1", filenames) 
#reads in all the files 
import <- mdply(filenames, read.table, header = TRUE, sep = "\t") 
#Assigns the index to each group of rows from each file 
import$index <- file.index[import$X1] 

#Gives you one big table to work with. 
#Fix your reversing issue 
import$Reqresponse.alt[import$Reqresponse == "a" & import$index %in% c(2,4,6,7,9,11,14,16,18,19,21,23,25,28,30,32,34,36)] <- "b" 
import$Reqresponse.alt[import$Reqresponse == "b" & import$index %in% c(2,4,6,7,9,11,14,16,18,19,21,23,25,28,30,32,34,36)] <- "a" 

import$Reqresponse <- import$Reqresponse.alt 
import$Reqresponse.alt <- NULL 

#Now your table should be clean 
#You can use plyr to to summarise your data 

import.summary <- ddply(import, .(index), summarise, 
         demo.mean = mean(demo), #functions you want to summarise with go here 
         demo.sd = sd(demo), 
         #etc 
         ) 

很显然,我没有你的实际数据一起工作来检查我没有犯过错误,但是这仅仅是那种现在运行非常漂亮,我的工作流程。

+0

没问题..... – alexwhan 2013-03-13 05:57:35

+1

当你把它们放在代码的同一行时,很难阅读你的评论。您可能会考虑将代码移到代码之前的行... – Dason 2013-03-13 06:00:08

+0

感谢您的提示,我会将其留在板上 – alexwhan 2013-03-13 22:35:54