我有一个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"))
我会感谢您的帮助!
答案 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=" ")))