我想以列B
为条件切换列C
和ID
;仅在ID = N
时切换。我的以下代码有效,但是有没有更简单/直观的方法?
df
ID A B C
Y 4 2 4
Y 1 5 7
N 8 3 NaN
N 6 2 NaN
Expected df
ID A B C
Y 4 2 4
Y 1 5 7
N 8 NaN 3
N 6 NaN 2
df$Bnew <- ifelse(df$ID== "N", df$C, df$B)
df$Cnew <- ifelse(df$ID== "N", df$B, df$C)
drops <- c("B", "C")
df <- df[, !names(df) %in% drops]
colnames(df)[colnames(df) == "Bnew"] <- "B"
colnames(df)[colnames(df) == "Cnew"] <- "C"
答案 0 :(得分:3)
在满足条件时切换列。
df[df$ID == "N", c("B", "C")] <- df[df$ID == "N", c("C", "B")]