Tuesday, 19 September 2017

r - 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


Answer



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)

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...