mercredi 12 mai 2021

R: locate element previous in vector within for loop and report in new column

I've looked through many older posts but nothing is really hitting the answer I need. In short: I have a data frame that contains observation data and the time of observation in days.

My goal is to add a column for weeks. I have already subsetted the data so that I only have the time vector at intervals of 7 (t == 7, 14, 21, etc). I just need to make a for loop that creates a new vector of "weeks" that I can then cbind to my data. I'd prefer it to be a character string so I can use it more easily in ggplot geom_historgram, but isn't as necessary as just creating the new vector successfully.

The tricky part of the data is that there is not an equal number of observations per time- t @ 28 has maybe 5x as many observations as t @7, etc.

I want to create code that evaluates what t is, then checks to see if it is greater than the last element in the t vector. If it isn't, then populate the week vector with the last value it did, and if so, then increase it by 1.

I know this is bad from a like, computer science/R perspective in a lot of ways, but any help would be useful:

#fake data (in reality this is a huge data set with many observations at intervals of 1 for t
L = rnorm(50, mean=10, sd=2)
t = c((rep.int(7,3)), (rep.int(14,6)), rep.int(21,8), rep.int(28,12), (rep.int(31, 5)), (rep.int(36,16)))
fake = cbind(L,t)

#create df that has only the observations that are at weekly time points
dayofweek = seq(7,120,7)
df = subset(fake, t %in% dayofweek)

#create empty week vector
week = c()

#for loop with if-else statement nested to populate the week vector
for (i in 1:length(dayofweek)){
  if (t = t[t-1]){
    week = i
  } else if (t > t[t-1]{
    week = i+1
  }
}

Thanks!!

Aucun commentaire:

Enregistrer un commentaire