我有数据框需要转换为列表,列表名称基于列
df <- data.frame("Name" = c("John", "Dora", "Dora", "Dora"), "V3" = c("Some text", "Some text 1","Some text 2","Some text 3"), stringsAsFactors = FALSE)
到目前为止,我已经尝试过
df.list <- split(df, seq(nrow(df)))
但这会根据行分别转换为列表
需要什么类似的东西
df.list <- structure(list(`John` = structure(list(V3 = structure(1L, .Label = "Some text",
class = "factor")), .Names = "V3", row.names = c(NA, -1L), class = "data.frame"),
`Dora` = structure(list(V3 = structure(c(1L, 2L, 3L), .Label = c("Some text 1",
"Some text 2",
"Some text 3"),
class = "factor")), .Names = "V3", row.names = c(NA, -3L), class = "data.frame")), .Names = c("John", "Dora"))
答案 0 :(得分:3)
OP的列在初始数据集中为character
类。如果我们需要具有list
列的输出factor
,请使用as.factor/factor
在split
之后或之前进行转换
lst <- lapply(split(df['V3'], df$Name), transform, V3 = factor(V3))
all.equal(lst, df.list[names(lst)], check.attributes = FALSE)
#[1] TRUE