slinel
slinel

Reputation: 61

Change multiple vector classes in R at once

I am trying to use change the classes of multiple vector at once, using %>% mutate_if

in an empty dataset of logical vectors. I can change them one by one with as.factor().

My dataset looks the following:

ID     code
pc01   cat
pc02   dog
pc03   cat
pc04   horse
pc01   dog
pc02   horse

Now, I post to you my whole code if it helps:

library(dplyr)
G <- as.factor(levels(as.factor(id)))
dat <- as.data.frame(G)
 
 datprep <- data.frame(matrix(vector(), length(G),
                          length(levels(as.factor(code)))
                          )
                       )
 colnames(datprep) = levels(as.factor(code))


datD <- cbind(datprep, datD)

# columns are logical, shall be factors.
datD %>% mutate_if(is.logical, as.factor)

Any suggestions?

Upvotes: 1

Views: 248

Answers (3)

Onyambu
Onyambu

Reputation: 79208

In base R you could do:

df <- type.convert(df)

or even

df <- rapply(df,factor,"character", how="replace")

Upvotes: 1

akrun
akrun

Reputation: 887008

In the new version of dplyr, we can also use across

library(dplyr)
df <- df %>%
     mutate(across(where(is.character), factor))

Upvotes: 1

DPH
DPH

Reputation: 4344

If I understood your problem correctly (not sure since there is no logical colum in you example just character), you have to include the ~ and . with mutate_if (and many others):

library(dplyr)

df <- dplyr::tibble(ID = c("pc01", "pc02", "pc03", "pc04", "pc01", "pc02"),
                    code = c("cat", "dog", "cat", "horse", "dog", "horse"))

df %>% 
  dplyr::mutate_if(is.character, ~ as.factor(.))

   ID    code 
  <fct> <fct>
1 pc01  cat  
2 pc02  dog  
3 pc03  cat  
4 pc04  horse
5 pc01  dog  
6 pc02  horse

The tilde "~" sinalizes a function (result is on the left) and the "." is stands for any column... I used is.character() as this is what your example columns are but you can change it to any other type of verification

Upvotes: 0

Related Questions