Easily reconstruct a string vector that has been split with string_split2df().

paste_conditional(x, id, sep = " ", names = TRUE, sort = TRUE)

Arguments

x

A character vector or a formula. If a vector: it represents the values to be pasted together. If a formula, it must be of the form my_string ~ id1 + id2 with on the left the character vector and on the right the (possibly many) identifiers. If a formula, the argument id must be a data frame.

id

A vector of identifiers, a list of identifiers (can be a data frame), or a data.frame. The identifiers can be a vector or a list of vectors. They represent which elements of x are to be pasted together.

When x is a formula, then id must be a data.frame containing the variables in the formula.

sep

A character scalar, default is " ". The value used to paste together the elements of x.

names

Logical scalar, default is TRUE. Whether to add, as names, the values of the identifiers.

sort

Logical scalar, default is TRUE. Whether to sort the results according to the identifiers.

Value

Returns a character vector. If the argument names is TRUE (default), the vector will have names equal to the values of the identifiers.

Examples


#
# let's paste together the letters of the alphabet

# first we create the identifier
id = rep(1:2, each = 13)
setNames(id, letters)
#> a b c d e f g h i j k l m n o p q r s t u v w x y z 
#> 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 

# now we conditionally paste together the letters
paste_conditional(letters, id, "")
#>               1               2 
#> "abcdefghijklm" "nopqrstuvwxyz" 

#
# using a formula

# we create a small data set based on mtcars
base_cars = within(mtcars, carname <- row.names(mtcars))
base_cars = head(base_cars, 10)

# we use two identifiers
paste_conditional(carname ~ gear + carb, base_cars, sep = ", ")
#>                     gear: 3, carb: 1                     gear: 3, carb: 2 
#>            "Hornet 4 Drive, Valiant"                  "Hornet Sportabout" 
#>                     gear: 3, carb: 4                     gear: 4, carb: 1 
#>                         "Duster 360"                         "Datsun 710" 
#>                     gear: 4, carb: 2                     gear: 4, carb: 4 
#>                "Merc 240D, Merc 230" "Mazda RX4, Mazda RX4 Wag, Merc 280"