[英]how to use apply function to take no names column mean?
I practiced the ?apply example in R documentation. 我在R文档中练习了?apply示例。
x<-cbind(x1=3,x2=c(4:1, 2:5))
dimnames(x)[[1]]<-letters[1:8]
apply(x,2,mean,trim = .2)
It is the outcome. 这是结果。
x1 x2
3 3
If i just want to take the x2's mean, like 如果我只想乘以x2的平均值,就像
x2
3
so i try 所以我尝试
apply(x,x[,2],mean)
and it is error:Error in if (d2 == 0L) { : missing value where TRUE/FALSE needed 这是错误的:if(d2 == 0L){中的错误:需要TRUE / FALSE的缺少值
so how could i do or improvement? 那我该怎么做或改善呢? thanks.
谢谢。
I'm not sure why you would want to use apply
there. 我不确定为什么要在此使用
apply
。 You can just do something like: 您可以执行以下操作:
mean(x[, "x2"], trim = .2)
# [1] 3
If you really wanted to use apply
, you can try something like: 如果您确实想使用
apply
,则可以尝试如下操作:
apply(x[, "x2", drop = FALSE], 2, mean, trim = .2)
# x2
# 3
## apply(x[, 2, drop = FALSE], 2, mean, trim = .2)
In other words, select the columns you're interested in as your dataset, and then apply whatever function you want. 换句话说,选择您感兴趣的列作为数据集,然后应用所需的任何函数。 Notice the use of
drop = FALSE
to prevent the single column from becoming a basic vector. 请注意,使用
drop = FALSE
可以防止单列成为基本向量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.