-1

I have a data.frame of unknown length with recordings of SkinTemp for different people (id). I would like to create a vector with time stamps (1/32s) for each id. I don't know how long each recording is.

df<-data.frame(
               SkinTemp=rnorm(65,37,0.5),
               id=rep(1:10,c(5,4,10,6,7,8,9,8,4,4)))

edit:

I have worked out how to do it using rle by adapting this answer Numbering rows within groups in a data frame

df$Time <- sequence(rle(as.character(df$id))$lengths)/32

edit 2:

I have realised this does not work exactly as it starts from 1/32 instead of 0. The dplyr answer using (row_number -1)/32 works better.

HCAI
  • 2,213
  • 8
  • 33
  • 65

1 Answers1

2

If I understand correctly, the time stamp is 1/32, 2/32, 3/32...n/32, where n is the number of rows per id.

So using dplyr to group by id should work:

EDIT: now uses (row_number() - 1) to start from 0.

library(dplyr)
set.seed(123)
df1 <- data.frame(SkinTemp = rnorm(65, 37, 0.5),
                  id = rep(1:10, c(5, 4, 10, 6, 7, 8, 9, 8, 4, 4)))

df1 <- df1 %>% 
  group_by(id) %>% 
  mutate(ts = (row_number() - 1) / 32) %>%
  ungroup()

# A tibble: 65 x 3
   SkinTemp    id     ts
      <dbl> <int>  <dbl>
 1     36.7     1 0     
 2     36.9     1 0.0312
 3     37.8     1 0.0625
 4     37.0     1 0.0938
 5     37.1     1 0.125 
 6     37.9     2 0     
 7     37.2     2 0.0312
 8     36.4     2 0.0625
 9     36.7     2 0.0938
10     36.8     3 0    # ... with 55 more rows
neilfws
  • 32,751
  • 5
  • 50
  • 63