Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a numerical df in r using factor df

I have a factor df that I would like it to be need it to be numerical/dummy. I used as.integer to each collumn and then made a cbind to the original data frame. Is there a way to do all columns at once?

data <- data.frame(
  x = c('a','b','c'),
  y = c('d','e','f'),
  z = c('g','h','i'),
  stringsAsFactors = TRUE
)

x_factor <- as.integer(data$x)
y_factor <- as.integer(data$y)
z_factor <- as.integer(data$z)

data_binded <- cbind(a,x_factor,y_factor,z_factor)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is dplyr solution:

library(dplyr)

data %>% 
  mutate(across(ends_with("factor"), as.numeric))
  x y z x_factor y_factor z_factor
1 a d g        1        1        1
2 b e h        2        2        2
3 c f i        3        3        3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading