R: fill new columns in data.frame based on row values by condition?

后端 未结 2 1165
执念已碎
执念已碎 2021-01-21 19:44

I want to create a new columns in my data.frame, based on values in my rows.

If \'type\" is not equal to \"a\", my \"new.area\" columns should contain the data from \"ar

相关标签:
2条回答
  • 2021-01-21 20:18

    Here is a base R solution using index subsetting ([) and match:

    my.df$new.area <- with(my.df, area[type == "a"][match(distance, distance[type == "a"])])
    

    which returns

    my.df
       distance area type new.area
    1         1   11    a       11
    2         2   12    a       12
    3         3   13    a       13
    4         4   14    a       14
    5         5   15    a       15
    6         1   16    b       11
    7         2   17    b       12
    8         3   18    b       13
    9         4   19    b       14
    10        5   20    b       15
    

    area[type == "a"] supplies the vector of possibilities. match is used to return the indices from this vector through the distance variable. with is used to avoid the repeated use of my.df$.

    0 讨论(0)
  • 2021-01-21 20:27

    We can use data.table

    library(data.table)
    setDT(my.df)[, new.area := area[type=="a"] , distance]
    my.df
    #     distance area type new.area
    # 1:        1   11    a       11
    # 2:        2   12    a       12
    # 3:        3   13    a       13
    # 4:        4   14    a       14
    # 5:        5   15    a       15
    # 6:        1   16    b       11
    # 7:        2   17    b       12
    # 8:        3   18    b       13
    # 9:        4   19    b       14
    #10:        5   20    b       15
    

    Or we can use the numeric index of distance as it is in a sequence

    with(my.df, area[type=="a"][distance])
    #[1] 11 12 13 14 15 11 12 13 14 15
    
    0 讨论(0)
提交回复
热议问题