0

I'm trying to change data types of the columns but in vain,what's wrong?

newtibble_1 <- newtibble_1 %>%
  type.convert(as.is = TRUE) %>%
  lapply(.[1:7],as.character)
Muska
  • 283
  • 4
  • 15

1 Answers1

1

With dplyr, the syntax would be to use mutate_at

library(dplyr)
newtibble_1 <- newtibble_1 %>%
                 type.convert(as.is = TRUE) %>%
                 mutate_at(1:7, as.character)

The output of lapplyis a list and may not be the one OP wanted. In the above code, the issue is in containerizing or blocking the code as there are a lot of things happening i.e. extracting the first 7 columns, then looping with lapply etc..

It can be done with {}.

mtcars %>% 
       {lapply(.[1:7], as.character)}

Or if we need to do this in pipe, then first do the extraction and then loop

mtcars %>%
      .[1:7] %>%
      lapply(as.character)

But, note that both the above will select the columns 1:7 and is not updating the original dataset columns. For that we may need to do the <- to the same selected columns


Or another option is map

library(purrr)
mtcars %>%
     map_at(1:7, as.character) %>%
     bind_cols
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Ok, 2 more questions: I use mutate to change 2 column's type and it doesn't work: `data_tibble_1 <- data_tibble %>% type.convert(as.is = TRUE) %>% mutate(Order_TMS_1 = as.character(Order_TMS_1), Cbm = as.numeric(str_replace(CBM,",","."))`. Type won't change. Second question is what gives this code: `type.convert(as.is = TRUE)` – Muska Jan 15 '20 at 01:57
  • @Muska the `type.convert` is applied on all character columns and change it to specified type based on the inherent type. i.e. `type.convert(c('1.2', '1.3', '1.5')) changes it to numeric while `type.convert(c('A', 'B'), as.is = TRUE)` converts to `character` (if we don't specify as.is = TRUE, it converts to `factor` – akrun Jan 15 '20 at 02:01
  • @Muska If the `type.convert` is not changing the type, it means that column have sssome elements that doesn't match i.e. `type.convert(c('1.2', '1.3', 'A'), as.is = TRUE)` will sstill be `character` because there is a letter in it and it is evaluated based on hierarchy – akrun Jan 15 '20 at 02:03
  • 1
    Thank you, now I understand! – Muska Jan 15 '20 at 19:22