假设我们创建了一个像这样的data.frame:
> 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
我们希望每天运行一个函数来根据结果返回一个值,如下所示:
nested_ifelse <- function(x){
ifelse (x > 1, mood <- "happy",
ifelse(x < 0, mood <- "sad",
mood <- "same as yesterday" ))
return(mood)
}
nested_ifelse()示例执行我想要的操作,我确信sapply()是正确的R函数,用函数的结果填充新列,但我不能把它们放在一起。
答案 0 :(得分:2)
您没有使用set.seed,因此该示例不可重现,但这应该为您提供所请求的向量:
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
答案 1 :(得分:2)
nested_ifelse应该是这样的:
nested_ifelse <- function(x){
mood <- ifelse (x > 1, "happy",
ifelse(x < 0, "sad",
"same as yesterday" ))
return(mood)
}
或更简单地说,
nested_ifelse <- function(x)
ifelse (x > 1, "happy",
ifelse(x < 0, "sad",
"same as yesterday" ))
你可以像这样使用:
d$mood2 <- sapply(d$v, nested_ifelse)
但实际上你不需要在这里打电话:
d$mood <- nested_ifelse(d$v)
就够了。
数据d应该是这样的......
d <- data.frame(v=rnorm(10))
答案 2 :(得分:0)
我不确定这是否适用于您的实际问题,但我想我会指出您并不总是需要嵌套ifelse
函数。有时您可以按顺序使用它们,只需确保顺序正确,这样就不会覆盖以前的值。
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))