gpt4 book ai didi

从相关输出中移除 NA

转载 作者:行者123 更新时间:2023-12-04 11:12:23 25 4
gpt4 key购买 nike

在大型数据集上生成相关矩阵时,有多个变量始终具有相同的值,因此无法进行相关并输出 NA。我的问题是如何删除具有这些 NA 值的所有行和列,或者在输出相关矩阵之前解决这个缺陷。所以例如在这个例子中......

df <- as.data.frame(matrix(sample(0:10, 3*8, replace=TRUE), ncol=3))
df$V4 <- rep(3, times = 8)
df$V5 <- rep(2, times = 8)
correlation <- cor(df)

我尝试了不同的方法来克服这个问题,首先是在相关计算中添加一个用途...

correlation_two <- cor(df, use = "pairwise.complete.obs")

但这没有影响。我也尝试过各种删除 NA 值的方法,但这些方法似乎都不起作用。

output1 <- na.omit(correlation)
output2 <- correlation[complete.cases(correlation),]
output3 <-correlation[,colSums(is.na(correlation))==0]
output4 <- correlation[, !colSums(is.na(correlation)) >1,drop=FALSE] #Removing columns
output4 <- output4[!rowSums(is.na(output4)) >1,drop=FALSE,]#Then rows

提前致谢。

最佳答案

我认为最好是预防问题而不是事后解决。

识别只有一个值的列:

select_for_correlation <- sapply(df,function(x)(length(unique(x))>1))

然后做分析:

res <- cor(df[,select_for_correlation])
> res
V1 V2 V3
V1 1.00000000 -0.06801818 -0.04626592
V2 -0.06801818 1.00000000 -0.21533949
V3 -0.04626592 -0.21533949 1.00000000

关于从相关输出中移除 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32524824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com