Hi,
Welcome to the RStudio community!
You are getting this error because you are trying to apply the function to the whole data frame instead of individual columns. Below I provide two ways of fixing this:
#Generate dummy data
set.seed(1) #Only needed for reproducibility
myData = data.frame(
col1 = as.character(runif(5)),
col2 = as.character(runif(5)),
col3 = as.character(runif(5))
)
#Check the class
sapply(myData, class)
#> col1 col2 col3
#> "character" "character" "character"
# Transform the columns using dplyr (Tidyverse) ...
library(dplyr)
myData = myData %>% mutate(across(everything(), as.numeric))
# OR Transform the columns using base R
for(column in colnames(myData)){
myData[,column] = as.numeric(myData[,column])
}
#Check again
sapply(myData, class)
#> col1 col2 col3
#> "numeric" "numeric" "numeric"
Created on 2022-05-17 by the reprex package (v2.0.1)
In both the Tidyverse (learn more here) and base R approach, you can apply this function to only a subset of the columns by substituting everything() or colnames(myData) by a vector of column names eg: c("col1", "col3")
Hope this helps,
PJ