mercredi 31 janvier 2018

R: create function or loop to change values based on two (or more) conditions

As you can probably see from the age of my account, i'm new here.

I'm running into problems with creating a function or loop to replace single values in a row, based on 2 or more conditions. Here is my sample dataset:

date timeslot volume lag1 1 2018-01-17 3 553 296 2 2018-01-17 4 NA 553 3 2018-01-18 1 NA NA 4 2018-01-18 2 NA NA 5 2018-01-18 3 NA NA 6 2018-01-18 4 NA NA

types are: Date, int, num, num

i want to create a function that replaces the NA from lag1 with the average of the last 5 simmulair timeslots. This value is calculated with:

w <- as.integer(mean(tail(data$volume[data$timeslot %in% c(1)],5), na.rm =TRUE ))

if i create a if or for loop, it returns "the condition has length > 1 and only the first element will be used"

So far i can only change all the lag1 values, or non.

The function should be something like this: if lag1 == NA & timeslot ==1 then change that row' value to w

i can't seem to figure this one out. Hope you guys can point me in the right direction.

Aucun commentaire:

Enregistrer un commentaire