0

I have a small problem, when trying to combine columns using paste, I combine the first column and the last result of the for loop. Tell me how to combine all the results of the for loop, and not just the last one?

if(i==1 | j==2){
                common.res <- data.table(res[,3])
                f <- data.table(paste(common.res1[,1],common.res[,]))
            }

My data:

x1 x2 x3
20 30 40
20 30 40
20 30 40

What do I get after I fasten the columns in the loop:

x1
20 40
20 40
20 40

What I want to get:

x1
20 30 40
20 30 40
20 30 40

1 Answers1

2

You can do this without a for loop using tidyr::unite():

library(tidyr)

res %>% unite(col = 'name_for_new_col', sep = ' ')

This will paste together all columns in res and put a space between each element. If you want to specify particular columns to do this on you can instead say:

res %>% unite(col = 'name_for_new_col', x1:x3, sep = ' ')

If you want to keep the old columns as well you can specify remove = FALSE within unite().


Alternatively, you can do it in base R using apply and paste:

res2 <- as.data.frame(apply(res, 1, paste, collapse = ' '))
names(res2)[1] <- 'nicer.name' #rename the single column

Or with just paste and a for loop:

df = data.frame(matrix(nrow = nrow(res), ncol = 1))
for (i in 1:nrow(res)) {
df[i,1] <- (paste(res[i,], collapse = ' '))
}
Elle
  • 998
  • 7
  • 12