i have a data.frame containing X columns (i'll use three in this example):
data<- data.frame('col1'=c('gama','zeta','omega'),'col2'=c('square','circle','triangle'),'col3'=c('bike','car','airplane'))
i want to 'sum' the values of each row of this data.frame placing on them a separator, the values are characters. i want to do this without using a for loop (cause my real data.frame is very large).
the 'paste' function requires multiple vectors as input (when the input is a list of character the output is wrong), but the 'ncol' (number of columns) of the real data.frame will change all time (is a dynamic generated data.frame).
i dont know how to do this using the 'paste' or the 'stringr::str_c' functions, but i tried them and both return a wrong formated unique vector. and 'rowSums' function only accepts numeric (and dont accepts a separator, but i could handle this).
CodePudding user response:
You can use apply
to apply the paste0
function on each row, and leverage the collapse
parameter:
data$new_col = apply(data, 1, paste0, collapse=", ")
Output:
col1 col2 col3 new_col
1 gama square bike gama, square, bike
2 zeta circle car zeta, circle, car
3 omega triangle airplane omega, triangle, airplane
CodePudding user response:
We can use
library(tidyr)
unite(data, new_col, everything(), sep = ", ", na.rm = TRUE, remove = FALSE)
-output
new_col col1 col2 col3
1 gama, square, bike gama square bike
2 zeta, circle, car zeta circle car
3 omega, triangle, airplane omega triangle airplane