如何基于R中相同列的值填充列中的值

时间:2018-07-31 10:12:56

标签: r dplyr

初始数据类似于

name <- c("a","a","a","a","a","b","b","b","b","b","c","c","c","c","c")
var1 <- c(0,1,0,0,1,0,0,1,0,1,1,0,0,0,1)
(data <- data.frame(name,var1))
#   name var1
#1     a    0
#2     a    1
#3     a    0
#4     a    0
#5     a    1
#6     b    0
#7     b    0
#8     b    1
#9     b    0
#10    b    1
#11    c    1
#12    c    0
#13    c    0
#14    c    0
#15    c    1

所需的输出:

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以在每组“名称”中使用cummax

data$var2 <- with(data, ave(var1, name, FUN = cummax))
data
#   name var1 var2
#1     a    0    0
#2     a    1    1
#3     a    0    1
#4     a    0    1
#5     a    1    1
#6     b    0    0
#7     b    0    0
#8     b    1    1
#9     b    0    1
#10    b    1    1
#11    c    1    1
#12    c    0    1
#13    c    0    1
#14    c    0    1
#15    c    1    1

由于您用dplyr标记了这个问题,所以您也可以这样做

library(dplyr)
data %>% 
  group_by(name) %>% 
  mutate(var2 = cummax(var1))