【发布时间】:2013-12-24 17:30:31
【问题描述】:
我有一个数据框 dfregion,如下所示:
dput(dfregion)
structure(list(region = structure(c(1L, 2L, 3L, 3L, 1L), .Label = c("East",
"New England", "Southeast"), class = "factor"), words = structure(c(4L,
2L, 1L, 3L, 5L), .Label = c("buildings, tallahassee", "center, mass, visitors",
"god, instruct, estimated", "seeks, metropolis, convey", "teaching, academic, metropolis"
), class = "factor")), .Names = c("region", "words"), row.names = c(NA,
-5L), class = "data.frame")
region words
1 East seeks, metropolis, convey
3 New England center, mass, visitors
4 Southeast buildings, tallahassee
5 Southeast god, instruct, estimated
6 East teaching, academic, metropolis
我正在按区域“融化”或“重塑”这个数据框,然后想将这些词粘贴在一起。
以下代码是我尝试过的:
dfregionnew<-dcast(dfregion, region ~ words,fun.aggregate= function(x) paste(x) )
dfregionnew<-dcast(dfregion, region ~ words, paste)
dfregionnew <- melt(dfregion,id=c("region"),variable_name="words")
最后,我做到了——但我不确定这是实现我想要的最佳方式
dfregionnew<-ddply(dfregion, .(region), mutate, index= paste0('words', 1:length(region)))
dfregionnew<-dcast(dfregionnew, region~ index, value.var ='words')
结果是以正确的方式重塑数据框,但每个“单词”列都是独立的。 随后,我尝试将这些列粘贴在一起,并且在这样做时遇到了各种错误。
dfregionnew$new<-lapply(dfregionnew[,2:ncol(dfregionnew)], paste, sep=",")
dfregionnew$new<-ldply(apply(dfregionnew, 1, function(x) data.frame(x = paste(x[2:ncol(dfregionnew], sep=",", collapse=NULL))))
dfregionnew$new <- apply( dfregionnew[ , 2:ncol(dfregionnew) ] , 1 , paste , sep = "," )
我能够通过执行类似于以下的操作来解决该问题:
dfregionnew$new <- apply( dfregionnew[ , 2:5] , 1 , paste , collapse = "," )
我想我真正的问题是,是否可以使用 melt 或 dcast 一步完成,而不必在输出后将各个列粘贴在一起。 我对提高我的技能非常感兴趣,并且会喜欢 R 中更快/更好的实践。 提前致谢!
【问题讨论】:
-
感谢您使用输入的
dput进行更新,但我仍然不清楚您想要的确切输出。您只想将“单词”列中的所有值按“区域”分组粘贴在一起? -
是的,我有兴趣拥有相同的两列,“区域”和“单词”,只是我希望单词是该区域中每个“行”中所有单词的串联.说东部地区,单词会是“寻找、大都会、传达、教学、学术、大都会”