2016-08-23 55 views
0

对于数据框中的每一行,我希望将值从一列复制到另一列,具体取决于第三列中的值。根据列的值从其他列获取值

我试着用组合for循环,如果函数来做到这一点:

## 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行中的值相同的值。

但它没有。有没有人能看到我犯的错误?

+1

您可以添加您最初data.frame和所需输出的例子吗? – thepule

+0

现在对你更有意义吗?不幸的是我不知道如何将表格添加到文本中... – Mathias

+0

如果你想添加一个表格,你可以简单地粘贴命令'dput(df)'的结果,其中'df'是你想要的数据框显示。 – thepule

回答

0

尝试以下操作:

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     2 
+0

不适用于我不幸:/ – Mathias

+0

这有点含糊。你有错误吗?我的代码输出是否高于你期望的正确值? – thepule

+0

是的,这就是我想要得到的输出......并且我也希望得到与我的代码一样的输出......我没有收到任何错误消息,但新变量(报复,特殊防范,general_prevention)中的所有值都是值“2” – Mathias

相关问题