user456789
user456789

Reputation: 351

combine substrings of columns

I have a data frame where I want to combine columns as strings but only take the first 3 characters of the respective lines.

Consider mtcars: I want to create a column comb consisting of the columns mpg and cyl but only taking the first two characters of mpg, separated by_.

The desired outcome of the first couple of lines for comb is:

comb
21_6
21_6
22_4
21_6

Upvotes: 1

Views: 302

Answers (2)

Ivo
Ivo

Reputation: 4200

with dplyr's mutate(), you can use substr() and paste0() (or paste(... sep = "_"), as pointed out above.

mtcars %>%
    mutate(comb = paste0(substr(as.character(mpg), 1, 2), "_", as.character(cyl)))

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

Use paste with substr:

mtcars$comb <- paste(substr(mtcars$mpg, 1, 2), mtcars$cyl, sep="_")

If the cyl column could contain more than one digit/character, and you only want the first one, then use substr a second time:

mtcars$comb <- paste(substr(mtcars$mpg, 1, 2), substr(mtcars$cyl, 1, 1), sep="_")

Upvotes: 4

Related Questions