R如何用来自不同级别数据集的匹配值替换数据集中的值

时间:2019-01-07 20:57:47

标签: r

给出两个数据帧:

df1 = data.frame(letters = c("A","B","3","D","5","G"),numbers = c(1:6))
df2 = data.frame(letters = c("C","E"), numbers = c(3,5))

df1
# letters   numbers
#    A         1
#    B         2
#    3         3
#    D         4
#    5         5
#    F         6 
df2
# letters   numbers
#    C         3
#    E         5

我得到此数据帧后需要做什么?

finalData

# letters   numbers
#    A         1
#    B         2
#    C         3
#    D         4
#    E         5
#    F         6 

我尝试了inner_join,但是我没有设法获得期望的结果。请让我知道要使用哪个功能!所以我可以采取下一步。谢谢!

1 个答案:

答案 0 :(得分:0)

这是一个可能的解决方案(与stringsAsFactors = TRUEFALSE一起使用)

# rbind matched values in df2 with df1 (without the rows corresponding to matches)
df <- rbind(df1[!df1$letters %in% df2$numbers,],df2[df2$numbers %in% df1$letters,])
df <- df[order(df$numbers),] # order the data frame
df
#    letters numbers
# 1        A       1
# 2        B       2
# 11       C       3
# 4        D       4
# 21       E       5
# 6        F       6

与数据

df1 <- data.frame(letters = c("A","B","3","D","5","F"),numbers = c(1:6)) # changed G to F
df2 <- data.frame(letters = c("C","E"), numbers = c(3,5))