【问题标题】:How to convert list given in a data frame to factor/numbers in R Data frame?如何将数据框中给出的列表转换为 R 数据框中的因子/数字?
【发布时间】:2019-07-24 05:53:52
【问题描述】:

mydf 用于可重现的目的。我有 mydf 数据框,我想将列表转换为 mydf 中的因素,但它会引发错误

mydf<-data.frame(col1=c("a","b"),col2=c("f","j"))
mydf$col1<-as.list(mydf$col1)
mydf$col2<-as.list(mydf$col2)
str(mydf)

这是我尝试将列表更改为因子/数字类型时遇到的错误

mydf$col1<-as.factor(mydf$col1)

Error in order(y) : unimplemented type 'list' in 'orderVector1'

我希望我的数据框 (mydf) 是预期的_df(无列表数据框)

expected_df<-data.frame(col1=c("a","b"),col2=c("f","j"))
str(expected_df)

如果您比较 str(mydf) 和 str(expected_df) ,则存在差异,因为我无法将列表更改为 mydf 数据框中的因子。有什么办法可以解决我的问题吗?

str(mydf)
'data.frame':   2 obs. of  2 variables:
$ col1:List of 2
..$ : Factor w/ 2 levels "a","b": 1
..$ : Factor w/ 2 levels "a","b": 2
$ col2:List of 2
..$ : Factor w/ 2 levels "f","j": 1
..$ : Factor w/ 2 levels "f","j": 2



str(expected_df)
'data.frame':   2 obs. of  2 variables:
$ col1: Factor w/ 2 levels "a","b": 1 2
$ col2: Factor w/ 2 levels "f","j": 1 2

【问题讨论】:

  • mydf[] &lt;- lapply(mydf, unlist).
  • 我有大约 2000 多个带有文本数据的文件,少数 json 文件有 20 列,其他有 18 列 [剩余 2 列不存在] ...所以这也是一个问题....我使用了您的代码,但它在[&lt;-.data.frame(*tmp*, , value = list(bwithbug = c("true", : 替换元素 10 有 2 行,需要 3 行) 中抛出了一些错误错误"
  • 如果您的问题是 JSON,请阅读this。

标签: r list dataframe dplyr


【解决方案1】:

您可以使用stringsAsFactors = TRUE

> mydf <- data.frame(col1 = c("a", "b"), col2 = c("f", "j"), stringsAsFactors = TRUE)
> mydf
  col1 col2
1    a    f
2    b    j
> mydf$col1
[1] a b
Levels: a b
> str(mydf)
'data.frame':   2 obs. of  2 variables:
$ col1: Factor w/ 2 levels "a","b": 1 2
$ col2: Factor w/ 2 levels "f","j": 1 2

【讨论】:

  • mydf 仅用于此处可重现的目的...实际数据很大,我没有创建该 df ,并且仅提供它,我不能使用此 stringsasfactors
  • 假设你得到了 mydf column 。您将如何将数据框中的列表转换为因子?那是我的问题...您的回答没有涵盖与数据框中给出的列表相关的任何内容!
【解决方案2】:

在这里聚会迟到了,但我想我会分享我的经验以供将来搜索。尝试将列转换为因子时,我也遇到了“顺序错误(y)”错误。我绕过它的方法是明确标记这些因素。在您的示例中,它会是这样的:

# instead of this:
# mydf$col1 <- as.factor(mydf$col1)

# using this:
mydf$col1 <- factor(mydf$col1, levels=c("a","b"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多