AlSub
AlSub

Reputation: 1155

Loop not working for character columns in R

I am trying to convert data class (from character to numeric) for certain df columns for a certain df inside a list; however when I run the next code a warning arises and the data class remains the same.

## inspecting class ##
class(df_list[["df"]][["col1"]])

//console output //
"character"


## function to return numeric ##
num_fun <- function(x){
             if(is.na(x)){
               return(NA)
             } else {
               as.numeric(x)
             }
}

numeric_columns <- c("col1", "col2", "col3")

# loop to convert character columns ##

for(i in seq_along(numeric_columns)){
      df_list[["df"]][, i] <-  lapply(
                                    df_list[["df"]][, i],
                                    num_fun)
}

// console output //
Warning messages:
1: In `[<-.data.frame`(`*tmp*`, , i, value = list(8, 8, 8,  ... :
  provided 1203 variables to replace 1 variables
2: In FUN(X[[i]], ...) : NAs introducidos por coerción


## verify ##
class(df_list[["df"]][["col1"]])

// console output //
"character"

Is there anyway to apply this function over specific column df list?

Upvotes: 0

Views: 79

Answers (2)

akrun
akrun

Reputation: 887128

We can use tidyverse approaches to do this. Extract the list element specify the vector of numeric_columns in across and convert to numeric

library(dplyr)
library(purrr)
df_list[["df"]] <- df_list[["df"]] %>%
                     mutate(across(numeric_columns), as.numeric))

Or using base R

Map(as.numeric, df_list[["df]][numeric_columns])

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388982

Try the following :

df_list[["df"]][numeric_columns] <- lapply(df_list[["df"]][numeric_columns], as.numeric)

This will convert the column in numeric_columns in df_list[["df"]] to numeric. NA would be kept as NA automatically.

Upvotes: 1

Related Questions