在某些列值上有条件地切换列

时间:2019-06-06 00:22:47

标签: r dataframe conditional-statements

我想以列B为条件切换列CID;仅在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"

1 个答案:

答案 0 :(得分:3)

在满足条件时切换列。

df[df$ID == "N", c("B", "C")] <- df[df$ID == "N", c("C", "B")]