I am looking to mutate data into one column seperated by ","
I can do this if I name each input column, but is there a way to do it without having to type out each V1...V11?
input = mtcars
colnames(input) = c('V1','V2','V3','V4','V5','V6','V7','V8','V9','V10','V11')
joined = mutate(output11, join = paste(V1,V2,V3,V4,V5,V6,V7,V8,V9,V10,V11, sep = ","))
output = select(joined, join)
CodePudding user response:
Couple of options -
- Use
tidyr::unite
-
tidyr::unite(input, join, dplyr::everything(), sep = ",")
# join
#Mazda RX4 21,6,160,110,3.9,2.62,16.46,0,1,4,4
#Mazda RX4 Wag 21,6,160,110,3.9,2.875,17.02,0,1,4,4
#Datsun 710 22.8,4,108,93,3.85,2.32,18.61,1,1,4,1
#Hornet 4 Drive 21.4,6,258,110,3.08,3.215,19.44,1,0,3,1
#Hornet Sportabout 18.7,8,360,175,3.15,3.44,17.02,0,0,3,2
#Valiant 18.1,6,225,105,2.76,3.46,20.22,1,0,3,1
#Duster 360 14.3,8,360,245,3.21,3.57,15.84,0,0,3,4
#Merc 240D 24.4,4,146.7,62,3.69,3.19,20,1,0,4,2
#Merc 230 22.8,4,140.8,95,3.92,3.15,22.9,1,0,4,2
#Merc 280 19.2,6,167.6,123,3.92,3.44,18.3,1,0,4,4
#...
#...
- Base R using
do.call
paste
input$join <- do.call(paste, c(input, sep = ","))
CodePudding user response:
Here is a combination of rowwise
and c_across
along with building a list:
library(dplyr)
library(tidyr)
mtcars %>%
rowwise() %>%
transmute(join = list(paste(c_across(everything()), collapse = ","))) %>%
unnest(join)
join
<chr>
1 21,6,160,110,3.9,2.62,16.46,0,1,4,4
2 21,6,160,110,3.9,2.875,17.02,0,1,4,4
3 22.8,4,108,93,3.85,2.32,18.61,1,1,4,1
4 21.4,6,258,110,3.08,3.215,19.44,1,0,3,1
5 18.7,8,360,175,3.15,3.44,17.02,0,0,3,2
6 18.1,6,225,105,2.76,3.46,20.22,1,0,3,1
7 14.3,8,360,245,3.21,3.57,15.84,0,0,3,4
8 24.4,4,146.7,62,3.69,3.19,20,1,0,4,2
9 22.8,4,140.8,95,3.92,3.15,22.9,1,0,4,2
10 19.2,6,167.6,123,3.92,3.44,18.3,1,0,4,4
# ... with 22 more rows
# i Use `print(n = ...)` to see more rows