Convenience function to paste together multiple columns into one. Analogous to tidyr::unite.

unite(.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.

Value

A data.table

See also

Examples

df <- CJ(x = c("a", NA), y = c("b", NA)) df
#> Key: <x, y> #> x y #> <char> <char> #> 1: <NA> <NA> #> 2: <NA> b #> 3: a <NA> #> 4: a b
# Treat missing value as NA, default df %>% unite("z", x:y, remove = FALSE)
#> Key: <x, y> #> x y z #> <char> <char> <char> #> 1: <NA> <NA> <NA> #> 2: <NA> b <NA> #> 3: a <NA> <NA> #> 4: a b a_b
# Treat missing value as character "NA" df %>% unite("z", x:y, na2char = TRUE, remove = FALSE)
#> Key: <x, y> #> x y z #> <char> <char> <char> #> 1: <NA> <NA> NA_NA #> 2: <NA> b NA_b #> 3: a <NA> a_NA #> 4: a b a_b
# the unite has memory, "z" would not be removed in new operations # here we remove the original columns ("x" and "y") df %>% unite("xy", x:y,remove = TRUE)
#> z xy #> <char> <char> #> 1: NA_NA <NA> #> 2: NA_b <NA> #> 3: a_NA <NA> #> 4: a_b a_b
# Select all columns iris %>% as.data.table %>% unite("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