Failed to use dimensions in a list

I have a list of dataframes that I want to convert two columns to numeric in each object of the list.

This is an example of the list I have:

y <- list(data.frame(Timestamp=c("2016-11-14","2016-11-14","2016-11-14","2016-11-14"),
             data.frame(Timestamp=c("2016-11-14 19:00:00","2016-11-14 19:10:00","2016-11-14 19:20:00","2016-11-14 19:30:00"),

I want to convert columns x1 and x2 of each object of the list to a numeric value with as.numeric but keeping the list.

I tried with this:

y[,-1] <- lapply(y[,-1] , as. numeric)

But this code doesn't work. I get the error

Error in y[, -1] : incorrect number of dimensions

I know y[,-1] would work in a single dataframe but I'm not sure how to handle it in a list.

Please some help.


It is because y is a list of 2 data.frames as sub-elements.
So, for instance, if you want to access the 1st sub element of y you need to use y[[1]] and not y[, 1]
Then, let's say that df is this first sub-element (df <- y[[1]])
If you want to convert every columns exept 1st one you can not do it with as.numeric(x[, -1]) because x[, -1] is 2 columns.
So you need to loop over columns to do the conversion

lapply(y, FUN = function(df) {
  df[, -1] = apply(df[, -1], 2, FUN = function(col) as.numeric(col))
map(y,~ .x %>% mutate(across(starts_with("x"),as.numeric)))

Thanks a lot!!

I was doing that at the beginning but I was wrong with the apply function, so I give up.

Thanks again!!


This works too!!

I tried both solutions.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.