2013-03-13 39 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