无法将数据.frame转换为R中的数值

nhaq1z21  于 5个月前  发布在  其他
关注(0)|答案(2)|浏览(43)

我正在使用R中的一个名为creditcard的框架,我想从同一个框架中计算变量Debt的相关性。然而,我不知道为什么,它给了我一个错误消息,说Debt必须是数字:
cor(Debt,Limit)中的错误:“x”必须是数字
我试着用下面的代码把它转换成一个数值变量:
Debt=as.numeric(as.character(Debt))
它仍然不起作用。它变成了数字,但已经失去了它以前的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个月了,直到最近才遇到这个问题,因为债务神秘地开始表现得像一个data.frame对象,而不是数字。任何想法,我可能会得到我的旧数字债务与所有400观察?提前感谢。

zwghvu4y

zwghvu4y1#

cor函数可以接受不同的输入。如果你给它一个矩阵或data.frame作为单个参数,它会给予你一个所有变量的相关矩阵,但是所有变量都必须是数值。
要获得creditcard Dataframe 的数值变量的所有相关性,您可以执行cor(creditcard[,sapply(credicard, is.numeric)])
否则,您可以通过为data.frame提供两个参数(cor(creditcard$Debt, creditcard$Limit)with(creditcard, cor(Debt, Limit)))来获取单个列之间的相关性。
您当前遇到的错误来自您正在调用的变量不可访问或类型错误。如果您调用cor(A, B),则A和B必须位于您当前的环境中。如果A和B是data.frame的列,则无法直接访问它们,因此您可以使用如上所示的with(creditcard, ...)公开data.frame的列,或者直接访问 Dataframe 内的列(creditcard$Acreditcard[,"A"]creditcard[["A"]])。

kyxcudwk

kyxcudwk2#

看起来我的猜测是正确的。正如在评论中提到的,基于错误消息,我假设你缺少了$-操作符来访问 Dataframe 中的变量(列)。
另一种选择,也在评论中提到,是使用with()代替。这里有一个基于{ISLR}Credit数据集的例子,我将Balance重命名为Debt

library(ISLR)
data(Credit)
names(Credit)
#>  [1] "ID"        "Income"    "Limit"     "Rating"    "Cards"     "Age"      
#>  [7] "Education" "Gender"    "Student"   "Married"   "Ethnicity" "Balance"
colnames(Credit)[ncol(Credit)] = "Debt"
with(Credit, cor(Limit, Debt))
#> [1] 0.8616973

字符串
创建于2023-12-08带有reprex v2.0.2

相关问题