首页 > 解决方案 > 为什么这两个对象不一样?

问题描述

我是 R 和 Stack Overflow 的新手,所以我的问题可能会犯很多错误,提前抱歉。

我正在使用插入符号的cor()功能,我花了一个小时来解决一个小问题,但我仍然不明白出了什么问题。基本上我有一个data.frame,我想标记高度相关的数字变量。所以我创建了一个数字变量的子集,除了SalePrice,它NA在测试集中有 s :

numericCols <- which(sapply(full[,!(names(full) %in% 'SalePrice')], is.numeric))   

然后

cor(full[,numericCols])    

给出一个错误:

cor(full[, numericCols]) 中的错误:“x”必须是数字。

除非我这样做:

numericCols2 <- which(sapply(full, is.numeric))    
numericCols2 <- numericCols2[-31] #dropping SalePrice manually    

它工作得很好。

当我这样做时numericCols == numericCols2,输出是:

LotFrontage     
TRUE    
LotArea    
TRUE    
# .    
# .   All true    
# .    
HouseAge    
FALSE    
isNew    
FALSE    
Remodeled    
FALSE    
BsmtFinSF    
FALSE    
PorchSF    
FALSE    

所有错误的都是我自己创建的变量,例如HouseAge

full$HouseAge <- full$YrSold - full$YearBuilt    

为什么会这样?

标签: r

解决方案


您的 data.frame 中的销售价格可能是字符或其他一些非数字列。这是一个重现您的问题的示例,并解释了为什么以一种方式执行此操作会出错,而以另一种方式执行此操作不会出错。

让我们模拟一些数据(我使用 MASS 包中的 iris 数据集并添加一个字符列“SalePrice”):

data(iris)
full <- cbind(data.frame(SalePrice=rep("NA", nrow(iris))),iris)

如果我们检查完整的数据框,我们将看到“SalePrice”列是字符:

str(full)
# 'data.frame': 150 obs. of  6 variables:
#   $ SalePrice   : Factor w/ 1 level "NA": 1 1 1 1 1 1 1 1 1 1 ...
# $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
# $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
# $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
# $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
# $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

现在让我们检查一下使用以下函数时会发生什么:

numericCols <- which(sapply(full[,!(names(full) %in% 'SalePrice')], is.numeric))
cor(full[, numericCols])
numericCols
# Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
# 1             2            3            4 

它返回一个带有子集中列索引的数字向量 full[,!(names(full) %in% 'SalePrice')] 正如您在我的数据框中看到的那样“SalePrice 是第一列,所以如果我排除它,然后将尝试在结果数据中查找所有数字列。我将得到列1,2,3 和 4 而不是 2,3,4 和 5

然后当我执行cor()函数时,我得到一个错误:

cor(full[, numericCols])
#Error in cor(full[, numericCols]) : 'x' must be numeric

您的其他方法有效,因为它返回正确的列索引:

numericCols2 <- which(sapply(full, is.numeric))  
numericCols2
#Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
#           2            3            4            5  

推荐阅读