Seifer
Seifer

Reputation: 53

Append to entries in a Dataframe

I want to append characters to column entries based on their column name. For example, I want to add _2019 to all entries which belong to a column that starts with the word "height". I have 9 columns in total.

For instance this works (illustrating what I did for the first 2 columns) but I was wondering if there was a more concise way:

new_df <- dataframe %>%
  mutate(height_p = paste0(height_p,"_2019")) %>%
  mutate(height_q = paste0(height_q,"_2019"))

I also tried mutate_at(starts_with("height"),vars(paste0("_2019")) but that just replaced all the entries with _2019!

EDIT: As suggested, I have added the first two rows with the first 3 columns from the dataset.

     height_p       height_q     height_s  
1  one_foot         two_feet     two_and_half_feet             
2  three_feet       one_foot      three_feet

Upvotes: 0

Views: 45

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388807

Try :

library(dplyr)
dataframe %>%  mutate_at(vars(starts_with("height")), ~paste0(., "_2019"))

Or in base R :

cols <- grep("^height", names(dataframe))
dataframe[cols] <- lapply(dataframe[cols], function(x) paste0(x, "_2019"))

Upvotes: 1

Related Questions