Assign value to group based on condition in column

后端 未结 3 1111
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 16:40

I have a data frame that looks like the following:

> df = data.frame(group = c(1,1,1,2,2,2,3,3,3), 
                 date = c(1,2,3,4,5,6,7,8,9),
                 


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 17:27

    Here is a base R option

     df$newValue = rep(df$date[which(df$value == 4)], table(df$group))
    

    Another alternative using lapply

    do.call(rbind, lapply(split(df, df$group), 
      function(x){x$newValue = rep(x$date[which(x$value == 4)], 
                        each = length(x$group)); x}))
    
    #    group date value newValue
    #1.1     1    1     3        2
    #1.2     1    2     4        2
    #1.3     1    3     3        2
    #2.4     2    4     4        4
    #2.5     2    5     5        4
    #2.6     2    6     6        4
    #3.7     3    7     6        8
    #3.8     3    8     4        8
    #3.9     3    9     9        8
    

提交回复
热议问题