Home > Software engineering >  How to break apart one numeric element in R?
How to break apart one numeric element in R?

Time:09-22

I have a vector here and each element is composed of a double-digit. I put it into a data frame. But is there any smart way to break down the elements? For example how to make two extra columns based on the number in the vector? 23 2 3 like this!

combination <- c(11, 12, 13, 14, 15, 16, 23, 24, 25, 26, 34, 35, 36, 45, 46, 56) # How to do it smartly?
crop.combinations <- rep(combination, each=num.rep)

CodePudding user response:

Assuming you only have 2-digits numbers you can use some elementary math operations:

df = data.frame(
  x = c(11, 12, 13, 14, 15, 16, 23, 24, 25, 26, 34, 35, 36, 45, 46, 56)
)

df$x1 = df$x %/% 10
df$x2 = df$x %%  10
#     x x1 x2
# 1  11  1  1
# 2  12  1  2
# 3  13  1  3
# 4  14  1  4
# 5  15  1  5
# 6  16  1  6
# 7  23  2  3
# 8  24  2  4
# 9  25  2  5
# 10 26  2  6
# 11 34  3  4
# 12 35  3  5
# 13 36  3  6
# 14 45  4  5
# 15 46  4  6
# 16 56  5  6

CodePudding user response:

You can use extract:

library(tidyr)
data.frame(combination) %>%
  extract(combination,
          into = c("1st", "2nd"),
          regex = "(.)(.)", 
          remove = FALSE)
   combination 1st 2nd
1           11   1   1
2           12   1   2
3           13   1   3
4           14   1   4
5           15   1   5
6           16   1   6
7           23   2   3
8           24   2   4
9           25   2   5
10          26   2   6
11          34   3   4
12          35   3   5
13          36   3   6
14          45   4   5
15          46   4   6
16          56   5   6

If you add convert = TRUE, the new columns will be converted to numeric.

CodePudding user response:

You can use tidyr::separate:

library(tidyr)
dat <- data.frame(combination = c(11, 12, 13, 14, 15, 16, 23, 24, 25, 26, 34, 35, 36, 45, 46, 56))

separate(dat, combination, 
         into = str_c("digit", seq(max(nchar(combination)))),
         sep = "(?<=[0-9])", 
         remove = FALSE)

output

   combination digit1 digit2
1           11      1      1
2           12      1      2
3           13      1      3
4           14      1      4
5           15      1      5
6           16      1      6
7           23      2      3
8           24      2      4
9           25      2      5
10          26      2      6
11          34      3      4
12          35      3      5
13          36      3      6
14          45      4      5
15          46      4      6
16          56      5      6

Or, with base R's strsplit:

as.data.frame(do.call(rbind, strsplit(as.character(combination), "")))

CodePudding user response:

substr() is another (simple) option.

> combination <- c(11, 12, 13, 14, 15, 16, 23, 24, 25, 26, 34, 35, 36, 45, 46, 56)
> substr(combination, 1, 1)
 [1] "1" "1" "1" "1" "1" "1" "2" "2" "2" "2" "3" "3" "3" "4" "4" "5"
> substr(combination, 2, 2)
 [1] "1" "2" "3" "4" "5" "6" "3" "4" "5" "6" "4" "5" "6" "5" "6" "6"
  •  Tags:  
  • r
  • Related