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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With