R数据框基于其他数据框的插入值

时间:2019-04-03 09:51:47

标签: r dataframe

我有2个数据框,如下所示:

df1
name    date       value df2_row df2_col
a    31-01-2019      1      1       1
b    31-01-2019      3      2       1
c    31-03-2019      5      3       3
d    31-03-2019      6      4       3
df2
name    31-01-2019 28-02-2019 31-03-2019       
a    
b    
c    
d    

我想像这样接收df2:

df2
name    31-01-2019     28-02-2019    31-03-2019       
a             1            NA             NA
b             3            NA             NA                 
c             NA           NA             5
d             NA           NA             6

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

看起来name中的datedf1与最终输出无关。假设您在name列之前有一列(NAcbind df2_rowdf2_col并为其分配value

df2[cbind(df1$df2_row, df1$df2_col)] <- df1$value

#  31-01-2019 28-02-2019 31-03-2019
#1          1         NA         NA
#2          3         NA         NA
#3         NA         NA          5
#4         NA         NA          6

数据

假设您的df2是这样的

df2 <- cbind(name = c("a", "b", "c", "d"), 
       setNames(data.frame(matrix(NA, ncol = 3, nrow = 4)), 
       c("31-01-2019","28-02-2019","31-03-2019"))) 

df2
#  name 31-01-2019 28-02-2019 31-03-2019
#1    a         NA         NA         NA
#2    b         NA         NA         NA
#3    c         NA         NA         NA
#4    d         NA         NA         NA

答案 1 :(得分:0)

我们可以将数据子集转换为matrix,它应该作为行/列索引

df2[-1][as.matrix(df1[c("df2_row", "df2_col")])] <- df1$value
df2
#  name 31-01-2019 28-02-2019 31-03-2019
#1    a          1         NA         NA
#2    b          3         NA         NA
#3    c         NA         NA          5
#4    d         NA         NA          6