Suppose we create a data.frame like this:
> hugs_per_day <- rnorm(10)
> hugs_per_day <- as.data.frame(hugs_per_day)
> hugs_per_day
hugs_per_day
1 -2.500457495
2 -0.204545274
3 -0.955424927
4 0.320184701
5 1.822908001
6 -0.058679520
7 -0.276004919
8 0.175341993
9 -0.137404974
10 0.005096691
And we want to run a function on each day to return a value based on the results, something like this:
nested_ifelse <- function(x){
ifelse (x > 1, mood <- "happy",
ifelse(x < 0, mood <- "sad",
mood <- "same as yesterday" ))
return(mood)
}
The nested_ifelse() example does what I want and I’m sure sapply() is the correct R function to populate a new column with results from the function, but I just can’t put the two together.
nested_ifelse should be like this:
or more simply,
and you can use like this:
but actually you don’t need to call sapply here:
is enough.
data d should be like this…