Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using paste within mutate function

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 = '_') ="

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading