【问题标题】:getting factors from a column dataset从列数据集中获取因子
【发布时间】:2020-03-28 03:12:19
【问题描述】:

我有一个带有“location_type”列的 R 数据集。 位置类型:15057 列表

head(ds $ location_type)

[[1]]
[1] "store"

[[2]]
[1] "store"     "service"

[[3]]
[1] "store"     "service"

[[4]]
[1] "store"     "service"     "regular appointment"

我试图将这些值转换为因子,因为现在它们显示为该变量内的列表,所以我得到以下因子

商店
店铺服务
门店服务定期预约

这个函数只产生但不适用

ds$location_type1 <- factor(ds$location_type, levels=c("store","store service","store service regular appointment"))

感谢您的帮助!

【问题讨论】:

    标签: r


    【解决方案1】:

    由于location_type 是一个列表,我们可以将paste 中的所有单个元素创建一个可以转换为factor 的值。

    ds$location_type <- factor(sapply(ds$location_type, paste, collapse = " "))
    

    【讨论】:

    • 谢谢。它不起作用,因为 unlist 会将 商店服务定期约会 分成 3 个附加值...Error in $(*tmp*, location_type1, value = c("store", : replacement has 24586 rows, data has 15057跨度>
    • @AndresMora 试试ds$location_type &lt;- factor(sapply(ds$location_type, paste, collapse = " "))
    【解决方案2】:

    我们也可以在tidyverse这样做

    library(purrr)
    library(stringr)
    library(dplyr)
    ds %>%
       mutate(location_type = factor(map_chr(location_type, str_c, collapse=" ")))
    

    【讨论】:

      猜你喜欢
      • 2013-04-25
      • 1970-01-01
      • 1970-01-01
      • 2016-05-09
      • 1970-01-01
      • 1970-01-01
      • 2019-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多