我有一个名为“ bank”的数据框,如下所示,它有大约4万行
age job salary marital education targeted default balance housing loan contact day month
58 management 100000 married tertiary yes no 2143 yes no unknown 5 may
duration campaign pdays previous poutcome response
261 1 -1 0 unknown no
我创建了以下函数,用于检查某些条件,然后返回一个值,该值作为新值添加到名为“ new”的新列下。
decide <- function(x){
if(x$marital=='married' & x$salary > 60000 & x$housing=='yes'){
return('yes')
}else if(x$marital=='single' & x$salary > 40000 & x$education=='tertiary'){
return('yes')
}else{
return('no')
}
}
然后,我将使用下面的循环在所有行上运行并导出新值
for(i in 1:nrow(bank)){
person<-bank[i,]
bank[i,'new']<-decide(person)
}
这满足了我的要求。
但是,当我尝试使用Apply函数而不是如下所示的for循环时,
bank$new1<-sapply(bank,decide)
它返回以下错误
错误:$运算符对原子向量无效
我编写的apply函数有什么问题,我可以要求您编写正确的for函数,如for循环吗?
尝试这样的事情:
decide <- function(x){
if(x["cyl"]==6 & x["disp"] > 150){
return('yes')
}else if(x["cyl"] == 8 & x["disp"] > 200){
return('yes')
}else{
return('no')
}
}
apply(mtcars, 1, decide)
稍微更优雅,更高效:
with(mtcars, ifelse(cyl == 6 & disp > 150, "yes", ifelse(cyl==8 & disp > 200, "no", "no")))
在这里,ifelse
可以处理矢量,这意味着您不必遍历整个数据帧。
要了解您的错误,请注意apply
-函数会将向量传递给该函数,并且不能使用$访问向量。看到:
vec <- c("a"=1, "b"=2)
vec
# a b
# 1 2
vec$a
# Error in vec$a : $ operator is invalid for atomic vectors
vec["a"]
# a
# 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句