【问题标题】:I'm trying to change a data frame variable to a factor variable but having issues我正在尝试将数据框变量更改为因子变量但遇到问题
【发布时间】:2020-11-29 00:20:21
【问题描述】:
> summary(CA_extract[2])
 REPORTING_YEAR
 Min.   :1990  
 1st Qu.:1995  
 Median :2010  
 Mean   :2007  
 3rd Qu.:2017  
 Max.   :2019  
> table(CA_extract[2])

1990 1995 2000 2005 2010 2015 2016 2017 2018 2019 
9081 5335 5787 5685 4888 4644 4590 4606 4581 4517 
> nrow(CA_extract)
[1] 53714
> ncol(CA_extract)
[1] 20
> class(CA_extract[2])
[1] "data.frame"
> summarise(CA_extract[2])
data frame with 0 columns and 1 row
> as.factor(CA_extract[2])
REPORTING_YEAR 
          <NA> 
Levels: c(1990, 1995, 2000, 2005, 2010, 2015, 2016, 2017, 2018, 2019)

> is.numeric(CA_extract[2])
[1] FALSE
> is.character(CA_extract[2])
[1] FALSE
> is.list(CA_extract[2])
[1] TRUE
> is.double(CA_extract[2])
[1] FALSE
> is.factor(CA_extract[2])
[1] FALSE
> is.vector(CA_extract[2])
[1] FALSE

我一直试图弄清楚如何将其更改为一个因子,据我所知,数据应该允许它工作,但每次运行它时,我都会得到一个带有一堆 N/As 的时髦列。任何帮助都会很棒,我能够让它在一个孤立的案例中工作,但我失去了解决方案,我无法将它集成到 for 循环中。

如果您需要更多信息,请告诉我。不知道如何在不下载与我相同的数据集的情况下提供可重现的数据。 (它是公开的)

【问题讨论】:

    标签: r dataframe r-factor


    【解决方案1】:

    简答:as.factor(CA_extract[[2]])

    问题与您如何仅使用单括号来引用数据框中的列有关。请参阅this answer(以及R documentation 中的相关部分)了解索引方法的不同之处。

    使用单括号来索引您的数据框会返回另一个数据框,正如您在测试 class(CA_extract[2]) 中看到的那样。比较str(CA_extract[2])str(CA_extract[[2]]) 的输出,区别应该很明显了。

    【讨论】:

    • 非常感谢这是完美的!我必须阅读一下,浪费了很多时间。
    【解决方案2】:

    你错过了一个逗号:

    CA_extract[, 2] <- factor(CA_extract[, 2])
    

    还有

    CA_extract$varname <- factor(CA_extract$varname)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      • 1970-01-01
      • 2014-08-30
      相关资源
      最近更新 更多