Convenience function to paste together multiple columns into one.

unite_dt(
  .data,
  united_colname,
  ...,
  sep = "_",
  remove = FALSE,
  na2char = FALSE
)

Arguments

.data

A data frame.

united_colname

The name of the new column, string only.

...

A selection of columns. If want to select all columns, pass "" to the parameter. See example.

sep

Separator to use between values.

remove

If TRUE, remove input columns from output data frame.

na2char

If FALSE, missing values would be merged into NA, otherwise NA is treated as character "NA". This is different from tidyr.

See also

Examples

df <- expand.grid(x = c("a", NA), y = c("b", NA))
df
#>      x    y
#> 1    a    b
#> 2 <NA>    b
#> 3    a <NA>
#> 4 <NA> <NA>

# Treat missing value as NA, default
df %>% unite_dt("z", x:y, remove = FALSE)
#>         x      y      z
#>    <fctr> <fctr> <char>
#> 1:      a      b    a_b
#> 2:   <NA>      b   <NA>
#> 3:      a   <NA>   <NA>
#> 4:   <NA>   <NA>   <NA>
# Treat missing value as character "NA"
df %>% unite_dt("z", x:y, na2char = TRUE, remove = FALSE)
#>         x      y      z
#>    <fctr> <fctr> <char>
#> 1:      a      b    a_b
#> 2:   <NA>      b   NA_b
#> 3:      a   <NA>   a_NA
#> 4:   <NA>   <NA>  NA_NA
df %>%
  unite_dt("xy", x:y)
#>         x      y     xy
#>    <fctr> <fctr> <char>
#> 1:      a      b    a_b
#> 2:   <NA>      b   <NA>
#> 3:      a   <NA>   <NA>
#> 4:   <NA>   <NA>   <NA>

# Select all columns
iris %>% unite_dt("merged_name",".")
#>      Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
#>             <num>       <num>        <num>       <num>    <fctr>
#>   1:          5.1         3.5          1.4         0.2    setosa
#>   2:          4.9         3.0          1.4         0.2    setosa
#>   3:          4.7         3.2          1.3         0.2    setosa
#>   4:          4.6         3.1          1.5         0.2    setosa
#>   5:          5.0         3.6          1.4         0.2    setosa
#>  ---                                                            
#> 146:          6.7         3.0          5.2         2.3 virginica
#> 147:          6.3         2.5          5.0         1.9 virginica
#> 148:          6.5         3.0          5.2         2.0 virginica
#> 149:          6.2         3.4          5.4         2.3 virginica
#> 150:          5.9         3.0          5.1         1.8 virginica
#>                    merged_name
#>                         <char>
#>   1:    5.1_3.5_1.4_0.2_setosa
#>   2:      4.9_3_1.4_0.2_setosa
#>   3:    4.7_3.2_1.3_0.2_setosa
#>   4:    4.6_3.1_1.5_0.2_setosa
#>   5:      5_3.6_1.4_0.2_setosa
#>  ---                          
#> 146:   6.7_3_5.2_2.3_virginica
#> 147:   6.3_2.5_5_1.9_virginica
#> 148:     6.5_3_5.2_2_virginica
#> 149: 6.2_3.4_5.4_2.3_virginica
#> 150:   5.9_3_5.1_1.8_virginica