1

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

6
  • will you always have the same amount of numbers in each array or could they both be 5 then later both be 10? Commented Mar 16, 2017 at 13:34
  • my real data.frames within my real list differ in length and type of observations. thanks Commented Mar 16, 2017 at 13:36
  • ok, will they be the same length as each other or can the length of each be different at the same time? Commented Mar 16, 2017 at 13:37
  • no, their length can be different at the same time, e.g. df1 = 22380 rows and df2 = 11654 rows, and the list contains df1 and df2. Commented Mar 16, 2017 at 13:39
  • my idea wouldnt work then Commented Mar 16, 2017 at 13:40

1 Answer 1

2

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) 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.