假设我有一个名为df
的数据框:
df <- data.frame(
A = 1:8,
B = rep(letters[1:4], each = 2),
C = rep(1:2, 4)
)
A B C
1 1 a 1
2 2 a 2
3 3 b 1
4 4 b 2
5 5 c 1
6 6 c 2
7 7 d 1
8 8 d 2
我希望交换B
列中的值,b
或c
,但不是a
或d
时的值在另一列C
上,即C = 1
时。所以目标data.frame是df1
:
df1 <- data.frame(
A = 1:8,
B = c("a", "a", "c", "b", "b", "c", "d", "c"),
C = rep(1:2, 4)
)
A B C
1 1 a 1
2 2 a 2
3 3 c 1
4 4 b 2
5 5 b 1
6 6 c 2
7 7 d 1
8 8 c 2
答案 0 :(得分:6)
您可以尝试chartr('bc', 'cb', df$B)
#[1] "a" "a" "c" "c" "b" "b" "d" "d"
,
C == 1
要在df$B[df$C == 1] <- chartr('bc', 'cb', df$B[df$C == 1])
上进行调整,然后
{{1}}
答案 1 :(得分:2)
# this will work generally
ic <- df$B == 'c'
ib <- df$B == 'b'
df$B[ic] <- 'b'
df$B[ib] <- 'c'
> df
A B
1 1 a
2 2 a
3 3 c
4 4 c
5 5 b
6 6 b
7 7 d
8 8 d
答案 2 :(得分:0)
gsub("_", "", ifelse(df$B == "b", "_c", ifelse(df$B == "c", "_b", as.character(df$B))))
#[1] "a" "a" "c" "c" "b" "b" "d" "d"
答案 3 :(得分:0)
dplyr
提供recode
一次替换多个值,如下所示。根据您问题中的新要求,我更新了以下代码,以提供所需的输出:
> library(dplyr)
> df
A B C
1 1 a 1
2 2 a 2
3 3 b 1
4 4 b 2
5 5 c 1
6 6 c 2
7 7 d 1
8 8 d 2
> for(i in 1:nrow(df)) {
if(df$C[i] == "1") {
df$B[i] <- recode(df$B[i], 'b' = 'c', 'c' = 'b')
}
}
> df
A B C
1 1 a 1
2 2 a 2
3 3 c 1
4 4 b 2
5 5 b 1
6 6 c 2
7 7 d 1
8 8 d 2
答案 4 :(得分:0)
a=which(df$B%in%letters[2:3]&df$C==1)
df[a,2]=df[rev(a),2];df
A B C
1 1 a 1
2 2 a 2
3 3 c 1
4 4 b 2
5 5 b 1
6 6 c 2
7 7 d 1
8 8 d 2