对于数据框中的每一行,我希望根据第三列中的值将值从一列复制到另一列。
我尝试使用一个组合的for循环和if函数来完成此操作:
## example
condition <- c("1","2","2","1","2","","3","3")
SZ01 <- c("1","1","1","1","1","","1","1")
SZ02 <- c("2","2","2","2","2","","2","2")
SZ03 <- c("3","3","3","3","3","","3","3")
df <- data.frame(cbind(condition,SZ01,SZ02,SZ03), stringsAsFactors = FALSE)
df$retribution <- NULL
df$special_prevention <- NULL
df$general_prevention <- NULL
for (i in 1:length(df$condition)){
if (df$condition[i] == 1){
df$retribution[i] <- df$SZ01[i]
df$special_prevention[i] <- df$SZ02[i]
df$general_prevention[i] <- df$SZ03[i]
}else if (df$condition[i] == 2) {
df$retribution[i] <- df$SZ02[i]
df$special_prevention[i] <- df$SZ03[i]
df$general_prevention[i] <- df$SZ01[i]
}else if (df$condition[i] == 3) {
df$retribution[i] <- df$SZ03[i]
df$special_prevention[i] <- df$SZ01[i]
df$general_prevention[i] <- df$SZ02[i]
} else {
df$retribution[i] <- "missing_condition"
df$special_prevention[i] <- "missing_condition"
df$general_prevention[i] <- "missing_condition"
}
}这似乎是有效的(没有错误消息),但从我的数据来看一定有什么问题。
例如,第1行包含condition == 1。这意味着,对于此行,df$retribution应该接收与df$SZ01的第1行中的值相同的值。
但事实并非如此,有没有人能看到我犯的错误?
发布于 2016-08-23 23:40:53
尝试以下操作:
condition <- c("1","2","2","1","2","","3","3")
SZ01 <- c("1","1","1","1","1","","1","1")
SZ02 <- c("2","2","2","2","2","","2","2")
SZ03 <- c("3","3","3","3","3","","3","3")
df <- data.frame(cbind(condition,SZ01,SZ02,SZ03), stringsAsFactors = F)
df$retribution <- ifelse(df$condition == "1", df$SZ01,
ifelse(df$condition == "2", df$SZ02,
ifelse(df$condition == "3", df$SZ03, "missing")))
df$special_prevention <- ifelse(df$condition == "1", df$SZ02,
ifelse(df$condition == "2", df$SZ03,
ifelse(df$condition == "3", df$SZ01, "missing")))
df$general_prevention <- ifelse(df$condition == "1", df$SZ03,
ifelse(df$condition == "2", df$SZ01,
ifelse(df$condition == "3", df$SZ02, "missing"))))输出:
df
condition SZ01 SZ02 SZ03 retribution special_prevention general_prevention
1 1 1 2 3 1 2 3
2 2 1 2 3 2 3 1
3 2 1 2 3 2 3 1
4 1 1 2 3 1 2 3
5 2 1 2 3 2 3 1
6 missing missing missing
7 3 1 2 3 3 1 2
8 3 1 2 3 3 1 2https://stackoverflow.com/questions/39104617
复制相似问题