【发布时间】:2020-08-26 14:37:21
【问题描述】:
无法在 for 循环中正确传递变量名或使用 lapply 函数。
当我尝试这个命令时没有循环/laaply 它可以工作并且我得到了值:
> boxplot.stats(df$price)$out
[1] 38.7 43.8 41.3 50.0 50.0 50.0 50.0 37.2 39.8 37.9 50.0
[12] 50.0 42.3 48.5 50.0 44.8 50.0 37.6 46.7 41.7 48.3 42.8
[23] 44.0 50.0 43.1 48.8 50.0 43.5 45.4 46.0 50.0 37.3 50.0
[34] 50.0 50.0 50.0 50.0
但是当我把它放在lapply or for-loop 下时,我得到Null,为什么?
df_numeric_names <- names(select_if(df, is.numeric))
df_numeric_names
[1] "price" "resid_area" "air_qual" "room_num" "age" "dist1" "dist2" "dist3"
[9] "dist4" "teachers" "poor_prop" "n_hos_beds" "n_hot_rooms" "rainfall" "parks" "Sold"
循环
for (feature in df_numeric_names){
outlier_values <- boxplot.stats(df$feature)$out
print(outlier_values)
}
- Output:
NULL
NULL
NULL
应用
lapply(df_numeric_names, function(x) {
boxplot.stats(df$x)$out
})
- output
[[1]]
NULL
[[2]]
NULL
[[3]]
NULL
[[4]]
NULL
[[5]]
NULL
这是一件相当简单的事情,但我不确定我做错了什么以及如何解决。
【问题讨论】:
-
不要使用
$,同时按字符值设置数据帧。