For each row in a data frame I want to copy a value from one column to another depending on a value in third column.
I tried to do it with a combined for loop and if fun
Try the following:
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"))))
Output:
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