运行factor()函数时在数据框的一个列上出现错误。

3

我有一个数据框,其中有几列。我想在其中一列上运行factor()函数,比如将其命名为my_col。最初我是这样做的

df[,"my_col"]<-factor((df[,"my_col"]))

它给出了以下错误

错误:'x'必须是原子的,以便对列表进行'sort.list'。你在列表上调用了'sort'吗?

参考 SO 上的类似问题后,我的问题得到了解决。

现在,如果我尝试以下代码而不是第一种方法,则可以完美地工作,而不会产生任何错误。

df$"my_col"<-factor(df$"my_col")

为什么会这样?通过 df$vec_name 和 df[,vec_name] 访问列之间有什么区别吗?

更新:

str(df)
Classes 'tbl_df', 'tbl' and 'data.frame':   160 obs. of  8 variables:
$ area     : int  1 1 1 1 1 1 1 1 1 1 ...
$ temp     : int  1 1 1 1 1 1 1 1 1 1 ...
$ size     : int  1 1 1 1 1 1 1 1 1 1 ...
$ storage  : int  1 1 1 1 1 2 2 2 2 2 ...
$ my_col   : int  1 2 3 4 5 1 2 3 4 5 ...
$ texture  : num  2.9 2.3 2.5 2.1 1.9 1.8 2.6 3 2.2 2 ...
$ flavor   : num  3.2 2.5 2.8 2.9 2.8 3 3.1 3 3.2 2.8 ...
$ moistness: num  3 2.6 2.8 2.4 2.2 1.7 2.4 2.9 2.5 1.9 ...
1个回答

4

您的数据是一个 tbl_df。 我没有您的数据,但我们可以使用 mtcars 示例来查看。

library(dplyr)

tbl_df(mtcars)[, "mpg"]
# Source: local data frame [32 x 1]
# 
#      mpg
#    (dbl)
# 1   21.0
# 2   21.0
# 3   22.8
# 4   21.4
# 5   18.7
# 6   18.1
# 7   14.3
# 8   24.4
# 9   22.8
# 10  19.2
# ..   ...

它仍然是一个数据框,在基础R中将被降为原子向量。dplyr:::`[.tbl_df` 不会像基础R中的[.data.frame 一样丢弃单个列。这就是为什么我们不能在其上运行factor() 的原因。

factor(tbl_df(mtcars)[, "mpg"])
# Error in sort.list(y) : 'x' must be atomic for 'sort.list'
# Have you called 'sort' on a list?

所以,您需要使用[[,例如df[["my_col"]],或者只需使用$

df[["my_col"]] <- factor(df[["my_col"]])

注意:在使用$运算符时,可以不用在列名周围加上引号。

df$my_col <- factor(df$my_col)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接