user10099944
user10099944

Reputation:

Change data types for multiple columns R

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)

Upvotes: 0

Views: 77

Answers (1)

akrun
akrun

Reputation: 887831

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

Upvotes: 0

Related Questions