Home > Net >  Using select and as.numeric at the same time in r
Using select and as.numeric at the same time in r

Time:01-31

The code to generate sample dataset is as below:

z = data.frame(a = c(1:4),b = as.character(c(1:4)),c = c('s,','d','g','y'))

zz = data.frame(a = c(5:8),b = as.numeric(c(5:8)),e = c(2,4,5,6))

zzz = data.frame(a = c(9:12),b = as.numeric(c(9:12)),r = c(4,8,6,5))

z4 = list(z,zz,zzz)

lapply(z4,function(x)x %>% select(a,b)) %>% bind_rows

The output is

> lapply(z4,function(x)x %>% select(a,b)) %>% bind_rows
Error in `bind_rows()`:
! Can't combine `..1$b` <character> and `..2$b` <double>.
Run `rlang::last_error()` to see where the error occurred.

Is there anyway to use select and as.numeric at the same time?

CodePudding user response:

We may automatically convert the list elements to its appropriate type with type.convert

library(purrr)
library(dplyr)
map_dfr(type.convert(z4, as.is = TRUE), ~ .x %>%
          select(a, b))

-output

    a  b
1   1  1
2   2  2
3   3  3
4   4  4
5   5  5
6   6  6
7   7  7
8   8  8
9   9  9
10 10 10
11 11 11
12 12 12

This may not work in all the conditions i.e. if there is a column with non-numeric element, it remains as character. In that case, instead of converting the columns to numeric (which could return NA for non-numeric), convert all the columns to character, bind them and later apply type.convert

map_dfr(z4, ~ .x %>%
            select(a, b) %>%
            mutate(across(everything(), as.character))) %>%
    type.convert(as.is = TRUE)
  • Related