如何将带有字符串的表转换为R中的向量列表?

时间:2019-03-14 13:14:47

标签: r

我有一个像这样的数据集

> data.frame("letter" = letters, "words" = paste0(1:26,letters, letters,",", rev(letters),letters,5:26, ",", letters, 1:24, rev(letters)))
   letter          words
1       a    1aa,za5,a1z
2       b    2bb,yb6,b2y
3       c    3cc,xc7,c3x
4       d    4dd,wd8,d4w
5       e    5ee,ve9,e5v
...

我想把这张桌子变成

[[a]]
[1] "1aa" "za5" "a1z"

[[b]]
[1] "2bb" "yb6" "b2y"

[[c]]
[1] "3cc" "xc7" "c3x"

[[d]]
[1] "4dd" "wd8" "d4w"

[[e]]
[1] "5ee" "ve9" "e5v"
...

我尝试使用一个对我有用的for循环,但是,当此数据帧的nrow增加时,它将花费更长的时间。我想知道是否有更清洁的方法?

非常感谢您的回答。 非常感谢你!

1 个答案:

答案 0 :(得分:1)

您正在寻找函数strsplit。试试:

df = data.frame("letter" = letters, "words" = paste0(1:26,letters, letters,",", rev(letters),letters,5:26, ",", letters, 1:24, rev(letters)))
strsplit(as.character(df$words),',',fixed= TRUE)

[[1]]
[1] "1aa" "za5" "a1z"

[[2]]
[1] "2bb" "yb6" "b2y"

[[3]]
[1] "3cc" "xc7" "c3x"

[[4]]
[1] "4dd" "wd8" "d4w"

[[5]]
[1] "5ee" "ve9" "e5v"