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