简体   繁体   中英

Convert from factor to numeric a column in data.frames within a list

Here an example of my two lists and relative code:

df1 = data.frame(a = c(1,1,1,2,3,3,4,4,5,6,6,7,8,9,9,10))
df2 = data.frame(a = c(1,2,2,2,3,4,5,5,6,6,7,8,9,9,10,10,11))

lst = list(df1, df2)

lst_table = lapply(lst, function(x) data.frame(table(x$a))) 

> class(lst_table[[1]]$Var1)
[1] "factor"
> class(lst_table[[2]]$Var1)
[1] "factor"

Because of my code purpose I need the column Var1 within each data.frame in the list to be a numeric vector.

Starting from How to convert a factor to an integer\\numeric without a loss of information? I applied the following code to the single data.frames and it works:

> df1$a = as.numeric(levels(df1$a))[df1$a]
> df2$a = as.numeric(levels(df2$a))[df2$a]

> class(df1$a)
[1] "numeric"
> class(df2$a)
[1] "numeric"

But how can I apply the above to a list?

I tried:

lst_table = lapply(lst_table, function(y) {y$Var1 = as.numeric(levels(y$Var1))[y$Var1]})

but it does not work.

Any suggestion? Thanks

I think the problem is that your function in your second lapply is only returning the vector of the numeric factor levels, not your entire data.frame . I believe the following should work:

foo <- function(y) {
  y$Var1 <- as.numeric(levels(y$Var1))[y$Var1]
  return(y)
}

lst_table <- lapply(lst_table, foo) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM