我正在 R 中使用一个名为creditcard 的数据框,我想计算来自同一数据框的变量 Debt 的相关性。但是,我不知道为什么,它给了我一条错误消息,说债务必须是数字:
cor(Debt,Limit) 中的错误:“x”必须是数字
我尝试使用以下代码将其转换为数字变量:
债务=as.numeric(as.character(债务))
还是不行。它变成了数字,但丢失了之前 400 个观测值的大部分,减少到只有 13 个......
> sapply(creditcard,class)
ID Income Limit
"integer" "numeric" "integer"
Rating Cards Age
"integer" "integer" "integer"
Education Gender Student
"integer" "factor" "factor"
Married Ethnicity Debt
"factor" "factor" "integer"
样本数据:
> dput(head(Debt))
c(NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_)
我已经使用信用卡数据框 3 个月了,直到最近才遇到这个问题,因为 Debt 神秘地开始表现得像 data.frame 对象而不是数字。有什么想法可以如何通过所有 400 个观察值收回我的旧数字债务吗?预先感谢。
cor
函数可以接受不同的输入。如果您提供一个矩阵或 data.frame 作为单个参数,它将为您提供所有变量的相关矩阵,但是所有变量都必须是数字。
要获取
creditcard
data.frame 的数值变量的所有相关性,您可以执行 cor(creditcard[,sapply(credicard, is.numeric)])
。
否则,您可以通过给定两个参数来获取 data.frame 的单列之间的相关性,即
cor(creditcard$Debt, creditcard$Limit)
或 with(creditcard, cor(Debt, Limit))
。