【发布时间】:2012-03-25 03:49:18
【问题描述】:
我有一个文本变量和一个分组变量。我想将文本变量按因子折叠成每行(组合)一个字符串。所以只要分组栏说m我想把文字分组在一起等等。我提供了前后的样本数据集。我正在为一个包写这个,到目前为止,我已经避免了对除wordcloud之外的其他包的所有依赖,并希望保持这种方式。
我怀疑rle 可能对cumsum 有用,但我无法弄清楚这一点。
提前谢谢你。
数据是什么样子的
text group
1 Computer is fun. Not too fun. m
2 No its not, its dumb. m
3 How can we be certain? f
4 There is no way. m
5 I distrust you. m
6 What are you talking about? f
7 Shall we move on? Good then. f
8 Im hungry. Lets eat. You already? m
我希望数据是什么样的
text group
1 Computer is fun. Not too fun. No its not, its dumb. m
2 How can we be certain? f
3 There is no way. I distrust you. m
4 What are you talking about? Shall we move on? Good then. f
5 Im hungry. Lets eat. You already? m
数据
dat <- structure(list(text = c("Computer is fun. Not too fun.", "No its not, its dumb.",
"How can we be certain?", "There is no way.", "I distrust you.",
"What are you talking about?", "Shall we move on? Good then.",
"Im hungry. Lets eat. You already?"), group = structure(c(2L,
2L, 1L, 2L, 2L, 1L, 1L, 2L), .Label = c("f", "m"), class = "factor")), .Names = c("text",
"group"), row.names = c(NA, 8L), class = "data.frame")
编辑:我发现我可以为组变量的每次运行添加唯一列:
x <- rle(as.character(dat$group))[[1]]
dat$new <- as.factor(rep(1:length(x), x))
产量:
text group new
1 Computer is fun. Not too fun. m 1
2 No its not, its dumb. m 1
3 How can we be certain? f 2
4 There is no way. m 3
5 I distrust you. m 3
6 What are you talking about? f 4
7 Shall we move on? Good then. f 4
8 Im hungry. Lets eat. You already? m 5
【问题讨论】:
标签: r