R“density.default(raw)中的错误:带有所有int值的data.frame中的参数'x'必须是数字”

时间:2017-01-29 04:09:11

标签: r dataframe types

当我的所有类型都是数字时,为什么会出现此错误?

> str(raw)
'data.frame':   404166147 obs. of  8 variables:
 $ piece_1_A  : int  0 0 0 0 0 0 0 0 0 0 ...
 $ piece_1_B  : int  0 0 0 0 0 0 0 0 0 0 ...
 $ piece_2_A : int  0 0 0 0 0 0 0 0 0 0 ...
 $ piece_2_B : int  0 0 0 0 0 0 0 0 0 0 ...
 $ item_1_A : int  0 0 0 0 0 0 0 0 0 0 ...
 $ item_1_B : int  0 0 0 0 0 0 0 0 0 0 ...
 $ piece_2_A: int  0 0 0 0 0 0 0 0 0 0 ...
 $ piece_2_B: int  0 0 0 0 0 0 0 0 0 0 ...
> sapply(raw, typeof)
  item_1_A   item_1_B  item_2_A  item_2_B  piece_1_A  piece_1_B piece_2_A
   "integer"    "integer"    "integer"    "integer"    "integer"    "integer"    "integer" 
piece_2_B 
   "integer" 
> density(raw[,1])
Error in density.default(raw[, 1]) : argument 'x' must be numeric

1 个答案:

答案 0 :(得分:0)

我建议检查变量的类。第一列可能是因子或字符,typeof仍然会返回整数。您需要将变量转换为类数字。

要查看typeofclass的行为,请尝试以下示例:

# load sample dataset
data(mtcars)
# check class and type of all variables
sapply(mtcars, class)
sapply(mtcars, typeof)
# convert gear variable to class factor
mtcars$gear <- as.factor(mtcars$gear)
# check class and type again
sapply(mtcars, class)
sapply(mtcars, typeof)