【问题标题】:Any efficient way to filter out multi-dim dataframe by measuring its correlation coefficient in R?通过测量 R 中的相关系数来过滤掉多维数据帧的任何有效方法?
【发布时间】: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


【解决方案1】:
mylist = do.call(rbind,
                 apply(persons_df, 1, function(x){
                     temp = cor.test(age_df$age, as.numeric(x))
                     data.frame(t = temp$statistic, p = temp$p.value)
                 }))
mylist
#           t            p
#a  -1.060264 3.488012e-01
#b  -2.292612 8.361623e-02
#c -16.785311 7.382895e-05
#d  -1.362776 2.446304e-01
#e  -1.922296 1.269356e-01
#f  -4.671259 9.509393e-03
#g  -3.719296 2.048710e-02
#h  -2.684663 5.496171e-02
#i -15.814635 9.341701e-05
#j  -2.423014 7.252635e-02

然后使用mylist 过滤掉你不想要的值。

【讨论】:

    猜你喜欢
    • 2018-07-17
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    相关资源
    最近更新 更多