2017-06-05 44 views
0

我想看看管道可能是有用的在這裏 -R中與管道更換值

p3Data[which(p3Data$memCond==1), "blockType"] <- 0 
p3Data[which(p3Data$memCond==2), "blockType"] <- 0 
p3Data[which(p3Data$memCond==3), "blockType"] <- 1 
p3Data[which(p3Data$memCond==4), "blockType"] <- 1 

p3Data[which(p3Data$memCond==1), "trialType"] <- 0 
p3Data[which(p3Data$memCond==2), "trialType"] <- 1 
p3Data[which(p3Data$memCond==3), "trialType"] <- 0 
p3Data[which(p3Data$memCond==4), "trialType"] <- 1 

如何使用%>%,使這更有效率?

回答

0

試試這個

library(magrittr) 
p3Data <- data.frame(memCond=sample(4,10,replace=TRUE)) 
p3Data <- p3Data %>% transform(blockType = (memCond-1) %/% 2, trialType = (memCond+1) %% 2) 
# memCond blockType trialType 
# 1  4   1   1 
# 2  1   0   0 
# 3  3   1   0 
# 4  2   0   1 
# 5  3   1   0 
# 6  4   1   1 
# 7  1   0   0 
# 8  2   0   1 
# 9  3   1   0 
# 10  4   1   1 

與包的最新版本,你應該能夠與

p3Data %<>% transform(blockType = (memCond-1) %/% 2, trialType = (memCond+1) %% 2) 

做得更好,但我無法測試它