Using ifelse() to replace NAs in one data frame by referencing another data frame of different length

后端 未结 3 1065
-上瘾入骨i
-上瘾入骨i 2020-12-09 13:36

I already reviewed the following two posts and think they might answer my question, although I\'m struggling to see how:

1) Conditional replacement of value

相关标签:
3条回答
  • 2020-12-09 14:17

    You may also use:

    df1$B[is.na(df1$B)] <- df2$B[match(df1$A[is.na(df1$B)],df2$A)]
    df1
    
    #             B          C  A
    # 1   1.7169811 2012-10-01  0
    # 2   0.3396226 2012-10-01  5
    # 3   4.0000000 2012-10-01 10
    # 4   0.1509434 2012-10-01 15
    # 5   0.0754717 2012-10-01 20
    # 6  20.0000000 2012-10-01 25
    # 7   1.7169811 2012-10-01  0
    # 8   0.3396226 2012-10-01  5
    # 9   5.0000000 2012-10-01 10
    # 10  5.0000000 2012-10-01 15
    
    0 讨论(0)
  • 2020-12-09 14:19

    Try the following code which takes your original statement and makes a small tweak in the TRUE argument of the ifelse function:

    > df1$B <- ifelse(is.na(df1$B) == TRUE, df2$B[df2$A %in% df1$A], df1$B)   
    #                         Switched '==' to '%in%' ---^
    > df1
                B          C  A
    1   1.7169811 2012-10-01  0
    2   0.3396226 2012-10-01  5
    3   4.0000000 2012-10-01 10
    4   0.1509434 2012-10-01 15
    5   0.0754717 2012-10-01 20
    6  20.0000000 2012-10-01 25
    7   1.7169811 2012-10-01  0
    8   0.3396226 2012-10-01  5
    9   5.0000000 2012-10-01 10
    10  5.0000000 2012-10-01 15
    
    0 讨论(0)
  • 2020-12-09 14:26
    df1[is.na(df1$B), c('A','C','B')] <- merge(df1[is.na(df1$B), -1], df2, by = 'A')
    
    0 讨论(0)
提交回复
热议问题