-1

I am looking for an efficient way to manipulate a lot of data in order to repeat the value of the last row of a group (given by the value in V1) in all the rows in the same column from the same group.

Input:

id V1 V2 V3
1  A  10 0
2  A  13 0
3  A  20 0
4  A  0  10
5  B  25 0
6  B  14 0
7  B  1  0
8  B  0  6

Output:

id V1 V2 V3
1  A  10 10
2  A  13 10
3  A  20 10
4  A  0  10
5  B  25 6
6  B  14 6
7  B  1  6
8  B  0  6
T-bo
  • 3
  • 1

2 Answers2

2

This should work with dplyr.

Assuming that your data is stored in a dataframe called df

df <- df %>% group_by(V1) %>% mutate(V3 = last(V3))

Relasta
  • 1,066
  • 8
  • 8
0

You can use group_by and mutate and last from dplyr package:


library(tibble)
library(dplyr)

your_data <- tribble(~id,  ~V1, ~V2,  ~V3,
1 , "A" , 10, 0,
2 , "A" , 13, 0,
3 , "A" , 20, 0,
4 , "A" , 0 , 10,
5 , "B" , 25, 0,
6 , "B" , 14, 0,
7 , "B" , 1 , 0,
8 , "B" , 0 , 6)


your_data %>%  
  group_by(V1) %>% 
  mutate(V3 = last(V3))
#> # A tibble: 8 x 4
#> # Groups: V1 [2]
#>      id V1       V2    V3
#>   <dbl> <chr> <dbl> <dbl>
#> 1  1.00 A     10.0  10.0 
#> 2  2.00 A     13.0  10.0 
#> 3  3.00 A     20.0  10.0 
#> 4  4.00 A      0    10.0 
#> 5  5.00 B     25.0   6.00
#> 6  6.00 B     14.0   6.00
#> 7  7.00 B      1.00  6.00
#> 8  8.00 B      0     6.00
Flo.P
  • 371
  • 2
  • 7
  • Do you know how i could do it if I had a metacategory (so if A & B would repeat for different values of a column V0 for example) ? – T-bo Feb 15 '18 at 15:53
  • I am not sure if I perfectly understand, but I would replace `group_by(V1)` by `group_by(V0, V1)` – Flo.P Feb 15 '18 at 15:55