【发布时间】:2019-06-26 19:00:08
【问题描述】:
我打算在 R 中找到从多维数据到一个数值向量的 Pearson 相关系数。基本上,我希望通过使用 Pearson 方法得到一个相关矩阵,想要保留行(也就是每列的特征) )通过使用某些相关系数作为阈值在多维数据中。但是,我暂时尝试了一些 R 实现来做到这一点,但没有得到正确的相关矩阵。我怎样才能得到这个?谁能指出我如何在 R 中轻松实现这一点?有什么想法吗?
可重现的例子
persons_df <- data.frame(person1=sample(1:20,10, replace = FALSE),
person2=as.factor(sample(10)),
person3=sample(1:25,10, replace = FALSE),
person4=sample(1:30,10, replace = FALSE),
person5=as.factor(sample(10)),
person6=as.factor(sample(10)))
row.names(persons_df) <-letters[1:10]
在persons_df中,给出了不同的行和列的特征。
我也有age_df,其中有每个人的年龄。
age_df <- data.frame(personID= colnames(persons_df),
age=sample(1:50, 6 , replace = FALSE))
我的初步尝试:
pearson_corr <- function(df1, df2, verbose=FALSE){
stopifnot(ncol(df1)==nrow(df2))
res <- as.data.frame()
lapply(colnames(df1), function(x){
lapply(x, rownames(y){
if(colnames(x) %in% rownames(df2)){
cor_mat <- stats::cor(y, df2$age, method = "pearson")
ncor <- ncol(cor_mat)
cmatt <- col(cor_mat)
ord <- order(-cmat, cor_mat, decreasing = TRUE)- (ncor*cmatt - ncor)
colnames(ord) <- colnames(cor_mat)
res <- cbind(ID=c(cold(ord), ID2=c(ord)))
res <- as.data.frame(cbind(out, cor=cor_mat[res]))
res <- cbind(res, cor=cor_mat[out])
}
})
})
return(final_df)
}
但上面的代码没有返回正确的相关矩阵。我想做什么 某个人的每个特征如何与他的年龄相关联。有没有有效的方法来实现这一点?有什么想法吗?
目标:
基本上,我想保留与年龄高度相关的特征。我没有更好的主意在 R 中执行此操作。谁能指出我如何在 R 中轻松有效地完成他的工作?谢谢
【问题讨论】:
-
您的预期输出示例会有所帮助。
标签: r dataframe correlation