如何使用apply函数取no names column是什么意思?

how to use apply function to take no names column mean?

我练习了 R 文档中的 ?apply 示例。

x<-cbind(x1=3,x2=c(4:1, 2:5))
dimnames(x)[[1]]<-letters[1:8]
apply(x,2,mean,trim = .2)

就是结果。

x1 x2 
 3  3

如果我只想取 x2 的平均值,比如

x2
 3

所以我试试

apply(x,x[,2],mean)

它是 error:Error in if (d2 == 0L) { : 缺失值 TRUE/FALSE 需要

那么我该如何做或改进?谢谢。

我不确定您为什么要在此处使用 apply。你可以做类似的事情:

mean(x[, "x2"], trim = .2)
# [1] 3

如果你真的想使用 apply,你可以尝试这样的方法:

apply(x[, "x2", drop = FALSE], 2, mean, trim = .2)
# x2 
#  3 

## apply(x[, 2, drop = FALSE], 2, mean, trim = .2)

换句话说,select 将您感兴趣的列作为您的数据集,然后应用您想要的任何函数。注意使用 drop = FALSE 来防止单列成为基本向量。