gpt4 book ai didi

r - 列表列表中的expand.grid之类的东西

转载 作者:行者123 更新时间:2023-12-03 20:49:09 24 4
gpt4 key购买 nike

我将三个文本文档存储为称为“ dlist”的列表列表:

dlist <- structure(list(name = c("a", "b", "c"), text = list(c("the", "quick", "brown"), c("fox", "jumps", "over", "the"), c("lazy", "dog"))), .Names = c("name", "text"))


在我的脑海中,我发现对这样的图片列表很有帮助:

   name  text
1 a c("the", "quick", "brown")
2 b c("fox", "jumps", "over", "the")
3 c c("lazy", "dog")


怎样像下面这样操作?这个想法是用图形表示的,因此可以将ggplot2融化的东西会很好。

  name  text
1 a the
2 a quick
3 a brown
4 b fox
5 b jumps
6 b over
7 b the
8 c lazy
9 c dog


每个单词一行,给出单词及其父文档。

我努力了:

> expand.grid(dlist)
name text
1 a the, quick, brown
2 b the, quick, brown
3 c the, quick, brown
4 a fox, jumps, over, the
5 b fox, jumps, over, the
6 c fox, jumps, over, the
7 a lazy, dog
8 b lazy, dog
9 c lazy, dog

> sapply(seq(1,3), function(x) (expand.grid(dlist$name[[x]], dlist$text[[x]])))
[,1] [,2] [,3]
Var1 factor,3 factor,4 factor,2
Var2 factor,3 factor,4 factor,2

unlist(dlist)
name1 name2 name3 text1 text2 text3 text4
"a" "b" "c" "the" "quick" "brown" "fox"
text5 text6 text7 text8 text9
"jumps" "over" "the" "lazy" "dog"

> sapply(seq(1,3), function(x) (cbind(dlist$name[[x]], dlist$text[[x]])))
[[1]]
[,1] [,2]
[1,] "a" "the"
[2,] "a" "quick"
[3,] "a" "brown"

[[2]]
[,1] [,2]
[1,] "b" "fox"
[2,] "b" "jumps"
[3,] "b" "over"
[4,] "b" "the"

[[3]]
[,1] [,2]
[1,] "c" "lazy"
[2,] "c" "dog"


可以公平地说,我对各种apply和plyr函数感到迷惑,并且不知道从哪里开始。我从未见过像上面的“ sapply”尝试那样的结果,并且也不理解。

最佳答案

如果将dlist转换为命名列表(我认为这是更适合的结构),则可以使用stack()获取所需的两列data.frame。

(第二行中的rev()setNames()调用只是调整列顺序和名称以匹配问题中显示的所需输出的许多方法之一。)

x <- setNames(dlist$text, dlist$name)
setNames(rev(stack(x)), c("name", "text"))
# name text
# 1 a the
# 2 a quick
# 3 a brown
# 4 b fox
# 5 b jumps
# 6 b over
# 7 b the
# 8 c lazy
# 9 c dog

关于r - 列表列表中的expand.grid之类的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16326354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com