从列数据集中获取因子

时间:2020-03-27 02:38:30

标签: r

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

head(ds $ location_type)

[[1]]
[1] "store"

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

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

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

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

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

此函数仅产生但NA不产生

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

我会感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

我们也可以在tidyverse

中执行此操作
library(purrr)
library(stringr)
library(dplyr)
ds %>%
   mutate(location_type = factor(map_chr(location_type, str_c, collapse=" ")))