Coerce specific column to "double" within a dataframe list

Viewed 65

Let's say I have a list of dataframes

 myList <- list(df1 = data.frame(A = as.character(sample(10)), B =
 rep(1:2, 10)), df2 = data.frame(A = as.character(sample(10)), B = rep(1:2, 10)) )

I want to coerce column A in each dataframe to double.

I'm trying:

myList =  sapply(myList,simplify = FALSE, function(x){  
x$A <- as.double(x$A) })

But this returns the coerced values, not even column with column names.

I also tried with dplyr and mutate_if, but with no success

1 Answers

We can use lapply with transform in base R

myList2 <- lapply(myList, transform, A = as.double(A))

Or use map with mutate from tidyverse

library(dplyr)
library(purrr)
myList2 <- map(myList, ~ .x %>%
                      mutate(A = as.double(A)))

The issue in the OP's code is that it is not returning the data i.e. 'x'.

myList2 <-  sapply(myList, simplify = FALSE,
       function(x){  
               x$A <- as.double(x$A)
               x
            })
Related