Ask Your Question
4

How can dplyr::mutate() be used to add multiple columns to a single column, while using a vector to specify the column names to be combined?

asked 2022-06-15 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-11-13 19:00:00 +0000

bukephalos gravatar image

To add multiple columns to a single column while using a vector to specify the column names to be combined, we can use the across() function within mutate():

df <- df %>% 
  mutate(across(c(col1, col2, col3), ~ paste(col1, col2, col3)))

In this example, col1, col2, and col3 are the column names to be combined, specified using a vector. The across() function takes a vector of column names (c(col1, col2, col3)) and applies the specified function (~ paste(col1, col2, col3)) to each of those columns. In this case, the function pastes the values of col1, col2, and col3 together, separated by a space. The resulting column(s) will have the same name as the original column(s) but with the added suffix _new.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-06-15 11:00:00 +0000

Seen: 13 times

Last updated: Nov 13 '21