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",
开发者_如何学Python 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:
nested_ifelse <- function(x){
mood <- ifelse (x > 1, "happy",
ifelse(x < 0, "sad",
"same as yesterday" ))
return(mood)
}
or more simply,
nested_ifelse <- function(x)
ifelse (x > 1, "happy",
ifelse(x < 0, "sad",
"same as yesterday" ))
and you can use like this:
d$mood2 <- sapply(d$v, nested_ifelse)
but actually you don't need to call sapply here:
d$mood <- nested_ifelse(d$v)
is enough.
data d should be like this...
d <- data.frame(v=rnorm(10))
You didn't use set.seed so the example is not reproducible but this should give you the requested vector:
hugs_per_day$mood <- c("sad","same as yesterday","happy" )[
findInterval( hugs_per_day$hugs_per_day, c(-Inf, 0, 1) ) ]
hugs_per_day
hugs_per_day mood
1 0.5747557 same as yesterday
2 -1.0236557 sad
3 -0.0151383 sad
4 -0.9359486 sad
5 1.1022975 happy
6 -0.4755931 sad
7 -0.7094400 sad
8 -0.5012581 sad
9 -1.6290935 sad
10 -1.1676193 sad
I'm not sure if this will work for your actual problem, but I thought I would point out that you don't always need to nest ifelse
functions. Sometimes you can use them sequentially, just make sure you get the order right so you don't over-write previous values.
set.seed(229)
hugs_per_day <- data.frame(hugs=rnorm(10))
hugs_per_day$mood <- "same as yesterday"
hugs_per_day$mood <- with(hugs_per_day, ifelse(hugs > 1, "happy", mood))
hugs_per_day$mood <- with(hugs_per_day, ifelse(hugs < 0, "sad", mood))
精彩评论