简体   繁体   English

应用数学函数时,如何从具有不同属性的元素的R列表中提取完整数据?

[英]How to extract the complete data from an R list with elements with different attributes when applying a mathematical function?

I performed a kmeansvar() on mtcars dataset and a quick peek at the contents of the output is shown below. 我对mtcars数据集执行了kmeansvar() ,并快速查看了输出内容,如下所示。

>require(ClustOfVar)
>fit <- kmeansvar(X.quanti = mtcars,init = 3)

>var_fit <- fit$var
> var_fit
$cluster1
     squared loading
mpg        0.8823383
cyl        0.8933205
disp       0.9184043
hp         0.7650133
wt         0.8245741

$cluster2
     squared loading
drat       0.7793067
am         0.8509076
gear       0.8415168

$cluster3
     squared loading
qsec       0.8388092
vs         0.7755302
carb       0.7018491

My next step requires me to extract the variable name with the maximum value of squared loading . 下一步需要提取具有squared loading最大值的变量名。

I have obviously used 'lapply' but my resultant output is this as shown below. 我显然使用了'lapply',但是我的输出如下所示。

$cluster1
[1] 0.9184043

$cluster2
[1] 0.8509076

$cluster3
[1] 0.8388092

My expected output is : 我的预期输出是:

$cluster1
     squared loading
disp       0.9184043

$cluster2
     squared loading

am         0.8509076


$cluster3
     squared loading
qsec       0.8388092

or, to be even more precise, my required values are : 或者,更确切地说,我需要的值是:

cluster1 disp
cluster2 am
cluster3 qsec

How do I extract the attributes of an element in a list? 如何提取列表中元素的属性?

We can loop over the list with sapply , use which.max to get the index of the max values, extract the row names corresponding to the index. 我们可以通过循环listsapply ,使用which.max得到的指数max值,提取对应于指数的行名。

sapply(var_fit, function(x) row.names(x)[which.max(x)])
#cluster1 cluster2 cluster3 
# "disp"     "am"   "qsec" 

I would also do it with lapply , with a little twist: 我也可以稍稍扭曲一下lapply

res1 <- lapply(var_fit, function(x) x[which.max(x),,drop=FALSE])

To get the names of the rows, I would have pretty much used the same method as the one proposed by @akrun. 为了获得行名,我将几乎使用与@akrun提出的方法相同的方法。 But the same result can be obtained by working on res1 : 但是通过对res1进行操作可以得到相同的结果:

res2 <- sapply(res1, rownames)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM