我在数据集A中有一列:1,1,2,2,3,4,4,4,5,5。 和数据集B B:1,2,3,4,5
有没有办法如何分别将B的值分配给A的值。
理想的结果必须是:
A B C
1 v v
1 b v
2 n b
2 m b
3 k n
4 m
4 m
4 m
4 m
5 k
5 k
答案 0 :(得分:2)
你可以尝试
C <- B[A]
#> C
# [1] "v" "v" "b" "b" "n" "m" "m" "m" "m" "k" "k"
如果要将此结果存储在数据框中,可以使用
length(B) <- length(A) # adapt the length of column B to that of column A
df <- cbind(A, B, C) # generate a matrix with three columns
df[is.na(df)] <- "" # remove the NA entries in column B (replace them with
# an empty string) in the rows where it is not defined
df <- as.data.frame(df) # convert the matrix into a data frame
#> df
# A B C
#1 1 v v
#2 1 b v
#3 2 n b
#4 2 m b
#5 3 k n
#6 4 m
#7 4 m
#8 4 m
#9 4 m
#10 5 k
#11 5 k
数据强>
A <- c(1, 1, 2, 2, 3, 4, 4, 4, 4, 5, 5)
B <- c("v", "b", "n", "m", "k")
但是,如果您已将A列和B列存储在数据框中,并且只需要生成C列,则可以使用df$C <- with(df, B[A])