I'm trying to create a new variable for time in seconds (as measured in 0.5hz, i.e. corresponding to 2 seconds) within trials depending on the variables time as measured in the experiment. Each trial should start with 0 then increase in steps of 2 seconds.
My data looks like this:
df_now <- data.frame(
time = 68.15:86,
trial_no = (c("1", "1", "1", "1", "1", "2", "2", "2", "3", "3", "3", "3", "4", "4", "4", "4", "4", "4")),
value = rnorm(18, 0, 3)
)
and should ideally look something like this
df_tobe <- data.frame(
time = 68.15:86,
trial_no = (c("1", "1", "1", "1", "1", "2", "2", "2", "3", "3", "3", "3", "4", "4", "4", "4", "4", "4")),
value = rnorm(18, 0, 3),
time.5hz = (c("0", "2", "2", "4", "4", "0", "2", "2", "0", "2","2", "4", "0", "2", "2", "4", "4", "6")),
value_mean_5hz = 'mean_value_per5hz'
)
(sorry for the crappy code)
In my data, much more decimals for time are involved, and time is not measured consistently (since it was only saved when a button was pressed).
Does anyone know what I could do? Thanks a lot!
library(dplyr)
df_now %>%
group_by(trial_no) %>%
mutate(time.5hz = ceiling((time - min(time))/2)) %>%
ungroup()
Result
# A tibble: 18 × 4
time trial_no value time.5hz
<dbl> <chr> <dbl> <dbl>
1 68.2 1 4.82 0
2 69.2 1 2.61 1
3 70.2 1 6.72 1
4 71.2 1 2.46 2
5 72.2 1 0.160 2
6 73.2 2 -3.82 0
7 74.2 2 -2.29 1
8 75.2 2 -5.55 1
9 76.2 3 -2.33 0
10 77.2 3 0.330 1
11 78.2 3 3.46 1
12 79.2 3 -2.36 2
13 80.2 4 0.501 0
14 81.2 4 -4.16 1
15 82.2 4 -1.73 1
16 83.2 4 1.05 2
17 84.2 4 -0.991 2
18 85.2 4 1.38 3