I want to create a new column using the values of first row of id in previous column

data i have

id <- c(1,1,1,2,2,3,3,4,4,4,5,5)
wt <- c(10,10,20,15,15,10,15,15,15,10,20,15)

df <- data.frame(id,wt)

data i want

bwt <- c(10,10,10,15,15,10,10,15,15,15,20,20)
df2 <- data.frame(id,wt,bwt)

I want to add a new column bwt to dataset df, new column is just the first row of column wt of perticular id

This is one way to do it using dplyr

library(dplyr)

df <- data.frame(
          id = c(1, 1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5),
          wt = c(10, 10, 20, 15, 15, 10, 15, 15, 15, 10, 20, 15)
)

df %>%
    group_by(id) %>% 
    mutate(bwt = first(wt))
#> # A tibble: 12 x 3
#> # Groups:   id [5]
#>       id    wt   bwt
#>    <dbl> <dbl> <dbl>
#>  1     1    10    10
#>  2     1    10    10
#>  3     1    20    10
#>  4     2    15    15
#>  5     2    15    15
#>  6     3    10    10
#>  7     3    15    10
#>  8     4    15    15
#>  9     4    15    15
#> 10     4    10    15
#> 11     5    20    20
#> 12     5    15    20

Created on 2020-11-13 by the reprex package (v0.3.0.9001)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.