Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R converting integer column to 3 factor columns based on digits

Tags:

r

I have a column of int's like this:

idNums
   2
 101
  34
  25
   8
 ...

I need to convert them to 3 factor columns like this:

digit1        digit2         digit3
  0             0              2
  1             0              1
  0             3              4
  0             2              5
  0             0              8
 ...           ...            ...

Any suggestions?

like image 249
screechOwl Avatar asked Dec 06 '22 17:12

screechOwl


1 Answers

Here's a fun solution using the modular arithmetic operators %% and %/%:

d <- c(2, 101, 34, 25, 8)
res <- data.frame(digit1 = d %/% 100, 
                  digit2 = d %% 100 %/% 10,  
                  digit3 = d %% 10)
#   digit1 digit2 digit3
# 1      0      0      2
# 2      1      0      1
# 3      0      3      4
# 4      0      2      5
# 5      0      0      8

Note that it has the minor -- but nice -- side benefit of returning numeric values for each of the columns. If you do, however, want factor columns instead, just follow up with this command:

res[] <- lapply(res, as.factor)

all(sapply(res, class)=="factor")
#[1] TRUE
like image 116
Josh O'Brien Avatar answered Apr 07 '23 11:04

Josh O'Brien