Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a variable based on order of observation in a dataframe - R

Tags:

r

dplyr

I want to add a variable value to a dataframe based on the order of the observation in the data frame.

… Subject Latency(s)
1   A     25
2   A     24
3   A     25
4   B     22
5   B     24
6   B     23

I want to add a third column called Trial and I want the values to be either T1, T2, or T3 based on the order of the observation and by Subject. So for example, Subject A would get T1 in row 1, T2 in row 2, and T3 in row 3. Then the same for subject B, and so on.

Right now my approach is to use group_by in dplyr to group by Subject. But I'm not sure then how to specify the new variable using mutate.

like image 895
Alex Avatar asked Jan 01 '26 00:01

Alex


1 Answers

Use mutate w/ row_number & group_by(Subject)

library(dplyr)

txt <- "ID Subject Latency(s)
1   A     25
2   A     24
3   A     25
4   B     22
5   B     24
6   B     23"

dat <- read.table(text = txt, header = TRUE)

dat <- dat %>% 
  group_by(Subject) %>% 
  mutate(Trial = paste0("T", row_number()))
dat  

#> # A tibble: 6 x 4
#> # Groups:   Subject [2]
#>      ID Subject Latency.s. Trial
#>   <int> <fct>        <int> <chr>
#> 1     1 A               25 T1   
#> 2     2 A               24 T2   
#> 3     3 A               25 T3   
#> 4     4 B               22 T1   
#> 5     5 B               24 T2   
#> 6     6 B               23 T3

Created on 2018-03-17 by the reprex package (v0.2.0).

like image 181
Tung Avatar answered Jan 03 '26 18:01

Tung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!