2

Imagine there are 100 columns, some of them categorical and most of them numerical. One of the column is Year.

I want to create a different dataset which shows the growth rate for each of the column. For example, if column one is Sales, I need sales growth rate; column two is income, I need corresponding Income growth rate. Please note there are 100 columns, so I am not looking to manually check growth rate for each column. I am assuming some sort of for loop is required.

#Here is an example for one column
           Diff_year <- growthFund$Year - lag(growthFund$Year)
           Diff_growth <- Sales - lag(Sales)
           Rate_percent <- (Diff_growth / Diff_year)/Sales * 100

azmath
  • 97
  • 6
  • 1
    Please make this question *reproducible*. This includes sample code you've attempted (including listing non-base R packages, and any errors/warnings received), sample *unambiguous* data (e.g., `dput(head(x))` or `data.frame(x=...,y=...)`), and intended output given that input. Refs: https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info. – r2evans Sep 15 '20 at 18:22
  • Can you show the logic for calculation – akrun Sep 15 '20 at 18:24
  • Ignore the categorical variables? – Chuck P Sep 15 '20 at 18:26
  • Yes, growth rate needed only for numerical variable – azmath Sep 15 '20 at 18:29
  • @azmath please don't put code in the comments. You can click on the gray "edit" label under your question, then at the bottom put three backticks in their own line, _then_ your code, _then_ three backticks to make a code block. – Allan Cameron Sep 15 '20 at 18:29

1 Answers1

1

If it is needed only for numeric variables, apply the function only across the columns that are numeric with is.numeric to find those columns

library(dplyr)
growthFund %>%
     mutate(across(where(is.numeric), Growth, .names = "{col}_new"))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Error: Problem with `mutate()` input `..1`. x unused argument (name = "{col}_growth") ℹ Input `..1` is `across(where(is.numeric), Growth, name = "{col}_growth")`. – azmath Sep 15 '20 at 18:35
  • @azmath sorry, a typo, it is `.names` – akrun Sep 15 '20 at 18:36