![](/img/trans.png)
[英]denormalize/coerce list (with nested vectors) to data.frame in R
[英]Coerce data.frame to list by row
從data.frame開始,例如:
df = read.table(text = "ref1 code1,code2
ref2 code3,code4,code5
ref3 code6", stringsAsFactors=F)
names(df) = c('id', 'codes')
print(df)
id codes
1 ref1 code1,code2
2 ref2 code3,code4,code5
3 ref3 code6
希望這樣的結果:
lst = list()
for(i in 1:3) lst[[df[i,1]]] = strsplit(df[i,2], ',')[[1]]
print(lst)
$ref1
[1] "code1" "code2"
$ref2
[1] "code3" "code4" "code5"
$ref3
[1] "code6"
沒有(緩慢的)迭代怎么可能到達這一點? as.list(df)
僅按列工作:
$id
[1] "ref1" "ref2" "ref3"
$codes
[1] "code1,code2" "code3,code4,code5" "code6"
提前致謝。
大概是這樣的:
lapply(split(df$codes,df$id),function(x) strsplit(x,split = ",")[[1]])
$ref1
[1] "code1" "code2"
$ref2
[1] "code3" "code4" "code5"
$ref3
[1] "code6"
下面提到的Ananda解決方案遠勝過恕我直言:
setNames(strsplit(df$codes, ","), df$id)
這是另一種方法。
> lst <- unlist(apply(df[,2, drop=FALSE], 1, strsplit, ","), recursive=FALSE)
> names(lst) <- df[,1]
$ref1
[1] "code1" "code2"
$ref2
[1] "code3" "code4" "code5"
$ref3
[1] "code6"
還使用setNames
來命名列表,如@Henrik的答案
> setNames(unlist(apply(df[,2, drop=FALSE], 1, strsplit, ","), recursive=FALSE), df$id)
您也可以嘗試
library(splitstackshape)
ll <- concat.split.list(data = df,
split.col = "codes",
drop = TRUE)[[2]]
names(ll) <- df$id
ll
# $ref1
# [1] "code1" "code2"
#
# $ref2
# [1] "code3" "code4" "code5"
#
# $ref3
# [1] "code6
在@Ananda Mahto的評論之后進行更新。 謝謝!
setNames(concat.split.list(df, "codes")[["codes_list"]], df$id)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.