Home > other >  Using paste within mutate function
Using paste within mutate function

Time:11-21

I have a data frame as below:

year <- c(2016,2017,2018)
xxx <- c(1,2,3)
yyy <- c(4,5,6)
df <- data.frame(year,xxx,yyy)

I would like to add a new column to this dataframe that has a column name based on one of the original columns, appended with some additional text such as:

paste(colnames(df[2]), 'test', sep = '_')

I also want to perform an operation of the values of this new column (e.g multiply it by a constant or construct it from original columns)

I tried to do this with mutate

df <- mutate(df, paste(colnames(df[2]), 'test', sep = '_') = df[2]*100)

But I receive the following:

Error: unexpected '=' in "df <- mutate(df, paste(colnames(df[2]), 'test', sep = '_') ="

CodePudding user response:

Use the := if we want to do the evaluation on the lhs

library(dplyr)
df <- df %>% 
    mutate(!! paste(names(df)[2], "test", sep = "_") := df[[2]] * 100)

-output

  year xxx yyy xxx_test
1 2016   1   4      100
2 2017   2   5      200
3 2018   3   6      300

or use across, to loop over the column and create new column by modifying the .names

df <- df %>%
    mutate(across(2, ~  .x * 100, .names = "{.col}_test"))

-output

df
  year xxx yyy xxx_test
1 2016   1   4      100
2 2017   2   5      200
3 2018   3   6      300
  • Related