我有两个数据框:

数据帧 1:

ColA ColB
Mat  Student
Por  Yes

数据帧 2:
ColA     ColB
Mat      0
Student  1
Por      2
Yes      3
No       4

我想通过用数据框 2 替换数据框 1 中的值来创建一个新的数据框

预期输出:
 ColA    ColB
 0        1
 2        3

最佳答案

循环遍历列和子集:

# example data
df1 <- read.table(text = "
  ColA ColB
Mat  Student
Por  Yes
", header = TRUE, stringsAsFactors = FALSE)

df2 <- read.table(text = "
  ColA     ColB
Mat      0
Student  1
Por      2
Yes      3
No       4
", header = TRUE, stringsAsFactors = FALSE)

# matrix output
sapply(df1, function(i) df2[ df2$ColA %in% i, "ColB"])
#      ColA ColB
# [1,]    0    1
# [2,]    2    3

# data.frame output
data.frame(lapply(df1, function(i) df2[ df2$ColA %in% i, "ColB"]))
#   ColA ColB
# 1    0    1
# 2    2    3

关于用另一个数据框的值替换一个值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51539109/

10-12 22:30