Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to covert column type of data frames that are inside a list?

Tags:

r

I have the following two data frames that in a list called df.list

df1 <- data.frame(name=c("a","b","c"),total=c("1","2","3"),other=c("100","200","300"))
df2 <- data.frame(name=c("d","e","f"),total=c("4","5","6"),other=c("100","200","300"))



df.list <- list(df1,df2)

[[1]]
  name total other
1    a     1   100
2    b     2   200
3    c     3   300

[[2]]
  name total other
1    d     4   100
2    e     5   200
3    f     6   300

I want to be able to go through each data frame in the list and covert the total and other columns to be numeric, and assign it back to df.list

I tried the following but it does not seem to work

lapply(df.list, function(x) as.numeric(x[2:3]))
like image 554
Nathan123 Avatar asked Feb 02 '26 03:02

Nathan123


2 Answers

We may use type.convert directly on the list

df.list2 <- type.convert(df.list, as.is = TRUE) 

-checking the structure

 str(df.list2)
List of 2
 $ :'data.frame':   3 obs. of  3 variables:
  ..$ name : chr [1:3] "a" "b" "c"
  ..$ total: int [1:3] 1 2 3
  ..$ other: int [1:3] 100 200 300
 $ :'data.frame':   3 obs. of  3 variables:
  ..$ name : chr [1:3] "d" "e" "f"
  ..$ total: int [1:3] 4 5 6
  ..$ other: int [1:3] 100 200 300

If we want to loop, then as.integer/as.numeric works on vectors. So, we need to loop again

df.list2 <- lapply(df.list, function(x) {
             x[2:3] <- lapply(x[2:3], as.integer)
             x})
like image 127
akrun Avatar answered Feb 03 '26 15:02

akrun


Or maybe this one:

library(purrr)

df.list %>%
        map(., ~mutate(.x, across(c(other, total), ~as.numeric(.x)))) %>%
        str()

List of 2
 $ :'data.frame':   3 obs. of  3 variables:
  ..$ name : chr [1:3] "a" "b" "c"
  ..$ total: num [1:3] 1 2 3
  ..$ other: num [1:3] 100 200 300
 $ :'data.frame':   3 obs. of  3 variables:
  ..$ name : chr [1:3] "d" "e" "f"
  ..$ total: num [1:3] 4 5 6
  ..$ other: num [1:3] 100 200 300
like image 22
Anoushiravan R Avatar answered Feb 03 '26 15:02

Anoushiravan R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!