RCN*_*RCN 3 r plyr dataframe 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
Run Code Online (Sandbox Code Playgroud)
我正在按区域"熔化"或"重塑"此数据框,然后将这些单词粘贴在一起.
以下代码是我尝试过的:
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")
Run Code Online (Sandbox Code Playgroud)
最后,我这样做了 - 但我不确定这是实现我想要的最佳方式
dfregionnew<-ddply(dfregion, .(region), mutate, index= paste0('words', 1:length(region)))
dfregionnew<-dcast(dfregionnew, region~ index, value.var ='words')
Run Code Online (Sandbox Code Playgroud)
结果是数据帧以正确的方式重新整形,但每个"单词"列都是独立的.随后,我尝试将这些列粘贴在一起,并在执行此操作时遇到各种错误.
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 = "," )
Run Code Online (Sandbox Code Playgroud)
我能够通过做类似于下面的事情来解决这个问题:
dfregionnew$new <- apply( dfregionnew[ , 2:5] , 1 , paste , collapse = "," )
Run Code Online (Sandbox Code Playgroud)
我想我真正的问题是,是否可以使用融合或dcast一步完成此操作,而不必在输出后将各个列粘贴在一起.我非常有兴趣提高我的技能,并希望在R中更快/更好的做法.提前感谢!
听起来你只想将"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
Run Code Online (Sandbox Code Playgroud)
无meltING或dcastING需要....
如果你不希望使用dcast从"reshape2",你可以尝试这样的事:
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
Run Code Online (Sandbox Code Playgroud)