Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (5.3k points)
edited by

I want to use dplyr's mutate() to create multiple new columns in a data frame. The column names and their contents should be dynamically generated.

Example data from iris:

require(dplyr)

data(iris)

iris <- tbl_df(iris)

I've created a function to mutate my new columns from the Petal. Width variable:

multipetal <- function(df, n) {

    varname <- paste("petal", n , sep=".")

    df <- mutate(df, varname = Petal.Width * n)  ## problem arises here

    df

}

Now I create a loop to build my columns:

for(i in 2:5) {

    iris <- multipetal(df=iris, n=i)

}

However, since mutate thinks varname is a literal variable name, the loop only creates one new variable (called varname) instead of four (called petal.2 - petal.5).

How can I get mutate() to use my dynamic name as variable name?

1 Answer

0 votes
by
edited by

To dynamically assign variable names using the dplyr package, you can do the following:

Create a function to dynamically assign variable names:

multisepal <- function(df, n) {

  varname <- paste("sepal", n , sep=".")

  mutate(df, !!varname := Sepal.Width * n)

}

To create the following columns in iris table:

data(iris)

iris2 <- tbl_df(iris)

for(i in 2:5) {

  iris2 <- multisepal(df=iris2, n=i)

}

head(iris2,5)

# A tibble: 5 x 9

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species sepal.2 sepal.3 sepal.4

         <dbl>       <dbl>        <dbl>       <dbl> <fct>     <dbl>   <dbl>   <dbl>

1          5.1         3.5          1.4         0.2 setosa      7      10.5    14  

2          4.9         3            1.4         0.2 setosa      6       9      12  

3          4.7         3.2          1.3         0.2 setosa      6.4     9.6    12.8

4          4.6         3.1          1.5         0.2 setosa      6.2     9.3    12.4

5          5           3.6          1.4         0.2 setosa      7.2    10.8    14.4

# ... with 1 more variable: sepal.5 <dbl>

If you wish to Learn R Programming visit this R Programming Tutorial by Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...