简体   繁体   中英

Repeating first observation within group with dplyr

I'm trying to repeat the first value within a group across all rows of that group. I had thought his would do it:

library(dplyr)
data.frame(g=c(1,1,2,2), v=c(1,2,3,4)) %>%
    group_by(g) %>% 
    mutate(f=first(v))
# Source: local data frame [4 x 3]
# Groups: g [2]
#
#       g     v     f
#   (dbl) (dbl) (dbl)
# 1     1     1     1
# 2     1     2     1
# 3     2     3     1
# 4     2     4     1

But I don't understand why f doesn't return as 1,1,3,3.

This should work

data.frame(g=c(1,1,2,2), v=c(1,2,3,4)) %>%
    group_by(g) %>%
    mutate(f = dplyr::first(v))

You may be picking up first from a different package. It does exist in the xts package and likely others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM