假设我们创建一个像这样的 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 函数,可以使用该函数的结果填充新列,但我无法将两者放在一起。
最佳答案
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)
但实际上你不需要在这里调用 sapply:
d$mood <- nested_ifelse(d$v)
够了。
数据d应该是这样的...
d <- data.frame(v=rnorm(10))
关于r - 嵌套 ifelse R 函数传递给 sapply() 以创建新的 data.frame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4476191/