Home > Software engineering >  How to apply function to several columns in R?
How to apply function to several columns in R?

Time:06-19

How can I apply this function to several columns of dataframe?

formatC(x, format="f", big.mark = ",", digits=0)

For example apply price and cost columns:

   df <- data.frame (origin = c("A","B","C","D","E","F","G","H","I","J"),
                  price = c(2334235,14545456,345452,74545451,3454545,64545450,1445,2551,4444,6550),
                  cost = c(10,12,20,2045450,-254545,14545452,14545453,94545450,-104545455,23),
                  change = c(10,12,-5,12,6,8,0.5,-2,5,-2))

CodePudding user response:

Use a lapply loop on the columns.

df <- data.frame (origin = c("A","B","C","D","E","F","G","H","I","J"),
                  price = c(2334235,14545456,345452,74545451,3454545,64545450,1445,2551,4444,6550),
                  cost = c(10,12,20,2045450,-254545,14545452,14545453,94545450,-104545455,23),
                  change = c(10,12,-5,12,6,8,0.5,-2,5,-2))

df[c("price","cost")] <- lapply(df[c("price","cost")], \(x) formatC(x, format="f", big.mark = ",", digits=0))
df
#>    origin      price         cost change
#> 1       A  2,334,235           10   10.0
#> 2       B 14,545,456           12   12.0
#> 3       C    345,452           20   -5.0
#> 4       D 74,545,451    2,045,450   12.0
#> 5       E  3,454,545     -254,545    6.0
#> 6       F 64,545,450   14,545,452    8.0
#> 7       G      1,445   14,545,453    0.5
#> 8       H      2,551   94,545,450   -2.0
#> 9       I      4,444 -104,545,455    5.0
#> 10      J      6,550           23   -2.0

Created on 2022-06-18 by the reprex package (v2.0.1)


Or define a columns vector first and then the code above.

cols <- c("price", "cost")
df[cols] <- lapply(df[cols], \(x) formatC(x, format="f", big.mark = ",", digits=0))

The result is the same as above.


The question is also tagged dplyr, here is a solution.

library(dplyr)

df %>%
  mutate(across(price:cost, ~ formatC(.x, format="f", big.mark = ",", digits=0)))
  • Related