running a function on every column

Hi, I am trying to run a function on every column of a data frame.

example data frame:

df <- data.frame(a = c(1:5), b = c(6:10), c = c(11:15))

function name is char_to_num(column).

my first solution was to manually call it

df$a = char_to_num(df$a)
df$b = char_to_num(df$b)
df$c = char_to_num(df$c)

but this is not reasonable and if I have more columns it is unnecessary work.

my first thought was to do a for loop but the values are not changing

for (i in colnames(df)){
    i = paste0("df$", i)
    i <- char_to_int(i)
}

I know I am accessing the 'i' variable and not the actually data frame but I want to emulate my first solution and unsure how to grab address of the column.

Here are two solutions, one with a for loop and one using functions from dplyr. There is also a little demonstration of why your method didn't work.

df <- data.frame(a = c(1:5), b = c(6:10), c = c(11:15))
#Make a toy function
TimesTwo <- function(x) x * 2

#Columns can be accessed by name using a string with [ ]
z <- "a"
df[z]
#>   a
#> 1 1
#> 2 2
#> 3 3
#> 4 4
#> 5 5

#The following does not work. z is treated as the actual column name
df$z
#> NULL

#Use a for loop
for (i in colnames(df)){
  df[i] <- TimesTwo(df[i])
}
df
#>    a  b  c
#> 1  2 12 22
#> 2  4 14 24
#> 3  6 16 26
#> 4  8 18 28
#> 5 10 20 30

#Using dplyr
library(dplyr)
df <- data.frame(a = c(1:5), b = c(6:10), c = c(11:15))
df <- mutate(df, across(.cols = everything(), .fns = TimesTwo))
df
#>    a  b  c
#> 1  2 12 22
#> 2  4 14 24
#> 3  6 16 26
#> 4  8 18 28
#> 5 10 20 30

Created on 2023-04-08 with reprex v2.0.2

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.