Replace NA values in dataframe variable with values from other dataframe by “ID”

后端 未结 1 1014
情书的邮戳
情书的邮戳 2021-01-06 14:42

I would like to know if there is a more concise way to replace NA values for a variable in a dataframe than what I did below. The code below seems to be longer

相关标签:
1条回答
  • 2021-01-06 15:26

    At the stage where there is only (breaks, fsites, bps and) df1 around:

    df1$Value <- ifelse(is.na(df1$Value), 
                                breaks$Value[match(df1$Break, breaks$Break)], df1$Value)
    
    #> df1
    #   Site Plot Break       Value
    #1     1    0     1  0.39330965
    #2     1    1     5  0.12465733
    #3     1    2     7  0.27380161
    #4     1    3     8  0.02728899
    #5     1    4    11 42.00000000
    #6     2    0     1  2.00000000
    #7     2    1     6  0.43971253
    #8     2    2    11  0.28972408
    #9     3    0     1  0.03642906
    #10    3    1     4  0.57746001
    #11    3    2     6  0.82037592
    #12    3    3     8  0.32321736
    #13    3    4     9  0.28637503
    #14    3    5    11 42.00000000
    
    #just to test with your `df4`
    > sort(df1$Value) == sort(df4$Value)
    [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
    
    0 讨论(0)
提交回复
热议问题