How can I combine multiple column values into one column?
I have a data frame called "stemmoutput" (see below):
X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
1 tanaman cabai
2 banget hama sakit tanaman
3 koramil nogosari melaks ecek hama tanaman padi ppl ds rambun
And I want to concatenate multiple column values into one column like this:
TEXT
1 tanaman cabai
2 banget hama sakit tanaman
3 koramil nogosari melaks ecek hama tanaman padi ppl ds rambun
I tried this code and it works
stemmoutput$TEXT <- with(stemmoutput, paste(X1,X2,X3,X4,X5,X6,X7,X8,X9,X10, sep=" "))
but is there any other way that is more efficient, without having to write down the column name one by one?
I also tried this code as shown below but that didn't work either.
for(i in names(stemmoutput)){
stemmoutput$TEXT <- with(stemmoutput, paste(i, sep=" "))}
source to share
Try do.call
library(stringr)
newdat <- data.frame(TEXT=str_trim(do.call(paste, stemmoutput)),
stringsAsFactors=FALSE)
newdat
# TEXT
#1 tanaman cabai
#2 banget hama sakit tanaman
#3 koramil nogosari melaks ecek hama tanaman padi ppl ds rambun
Better to use ,
as a separator if the column
TEXT <- gsub(', [^A-Za-z]+', '', do.call(paste, c(stemmoutput, sep=', ')))
newdat <- data.frame(TEXT, stringsAsFactors=FALSE)
newdat
# TEXT
#1 tanaman, cabai
#2 banget, hama, sakit, tanaman
#3 koramil, nogosari, melaks, ecek, hama, tanaman, padi, ppl, ds, rambun
source to share
Here's another idea using tidyr
If you unite
only want to use columns from X1
to X10
:
library(tidyr)
unite(stemmoutput, TEXT, num_range("X", 1:10), sep = " ")
If you want to concatenate all columns, follow these steps:
unite(stemmoutput, TEXT, everything(), sep = " ")
Benchmarks
I tried two approaches to the reference because I suspected it unite
would be much faster than do.call
that, but they turned out to be pretty equivalent:
df <- data.frame(replicate(10,sample(paste0(
sample(LETTERS[1:10]), collapse = ""), 10e5, replace = TRUE)))
mbm <- microbenchmark(
akrun = data.frame(TEXT=str_trim(do.call(paste, df)), stringsAsFactors=FALSE),
steven = unite(df, TEXT, everything(), sep = " "),
times = 50
)
# Unit: milliseconds
# expr min lq mean median uq max neval cld
# akrun 1117.1350 1132.3861 1146.3943 1136.3094 1145.076 1232.5633 50 b
# steven 910.7432 924.0386 927.8614 927.7224 929.649 995.3584 50 a
source to share