融合数据框并将列中的值粘贴在一起

时间:2013-12-24 17:30:32

标签: r dataframe plyr reshape2

我有一个数据帧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 = "," )

我想我真正的问题是,是否可以使用融合或dcast一步完成此操作,而不必在输出后将各个列粘贴在一起。 我对提高自己的技能非常感兴趣,并希望在R中更快/更好的做法。 提前致谢!

1 个答案:

答案 0 :(得分:7)

听起来您只想将“word”列中的值粘贴在一起,在这种情况下,您应该只能使用aggregate,如下所示:

aggregate(words ~ region, dfregion, paste)
#        region                                                     words
# 1        East seeks, metropolis, convey, teaching, academic, metropolis
# 2 New England                                    center, mass, visitors
# 3   Southeast          buildings, tallahassee, god, instruct, estimated

没有meltdcast需要......


如果您 想要使用“reshape2”中的dcast,您可以尝试这样的事情:

dcast(dfregion, region ~ "WORDS", value.var="words", 
      fun.aggregate=function(x) paste(x, collapse = ", "))
#        region                                                     WORDS
# 1        East seeks, metropolis, convey, teaching, academic, metropolis
# 2 New England                                    center, mass, visitors
# 3   Southeast          buildings, tallahassee, god, instruct, estimated
相关问题