如何将一个矩阵中的值替换为另一个矩阵

时间:2017-11-08 07:25:38

标签: r

我有两个数据框:

DF1:

Person|BreakfastSpent|LunchSpent|DinnerSpent
a     |100           |200       |21
b     |12            |65        |   
c     |14            |294       |46
d     |53            |          |55
e     |              |23        |7
f     |49            |54        |95
g     |61            |87        |47
h     |              |41        |32
i     |1             |          |107

和df2:

Person|Expenditure_BrkFast|Expenditure_Lunch|Expenditure_Dinner
a     |213                |79               |0
d     |265                |35               |543
f     |342                |98               |76
g     |119                |0                |0

如果可用,我想从df1值替换df2值。有人可以告诉我一个简短的方法来实现这个目标吗?

2 个答案:

答案 0 :(得分:1)

由于列的顺序相同,我们可以将Mapmatch一起使用(假设两个数据集为data.frame s)

df1[-1] <- Map(function(x, y) replace(x, match(df2$Person, 
                  df1$Person, nomatch = 0), y), df1[-1], df2[-1])

或另一种选择是使用row/column索引来分配

df1[-1][cbind(match(df2$Person, df1$Person), rep(1:3, each = nrow(df2)))] <- unlist(df2[-1])
df1
#  Person BreakfastSpent LunchSpent DinnerSpent
#1      a            213         79           0
#2      b             12         65          NA
#3      c             14        294          46
#4      d            265         35         543
#5      e             NA         23           7
#6      f            342         98          76
#7      g            119          0           0
#8      h             NA         41          32
#9      i              1         NA         107

答案 1 :(得分:1)

试试这个

names(df2) <- names(df1)
a <- df2[df2$Person %in% df1$Person, ]
b <- df1[!df1$Person %in% df2$Person, ]
rbind(a, b)