简体   繁体   English

如何将R apply函数的结果保存到矩阵中?

[英]How to save the result of R apply functions into a matrix?

Suppose I have a data set X, that has dimension 100 x 10. I want to apply a set of functions to each column, and save the results in a new data frame with the same column headers. 假设我有一个数据集X,其维度为100 x 10.我想将一组函数应用于每一列,并将结果保存在具有相同列标题的新数据框中。

Example

M <- matrix(rexp(200, rate=.1), ncol=20)
M_df <- as.data.frame(M)
row1 <- apply(M_df,2,mean)
row2 <- apply(M_df,2,var)
row3 <- apply(M_df,2,sum)

I want to make a new matrix that is comprised of row1, row2, and row3 which has the same column headers as M_df. 我想创建一个由row1,row2和row3组成的新矩阵,它与M_df具有相同的列标题。

Thanks! 谢谢! Max 马克斯

Try this: 尝试这个:

apply(M_df,2,function(x) c(mean = mean(x),var = var(x),sum = sum(x)))

Although, keep in mind that the first thing that apply does is convert M_df back to a matrix, so there's not much point in converting it to a data frame before you really have to. 虽然,请记住,首先apply是将M_df转换回矩阵,因此在您真正需要之前将它转换为数据帧并没有多大意义。

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

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