Factor () for a multidimensional data structure in R

Here is an example:

Matrix type

     [,1] [,2]
[1,]    1    4
[2,]    2    3
[3,]    3    2
[4,]    4    1
[5,]    1    4
[6,]    2    3
[7,]    3    2
[8,]    4    1

And I want to get some levels, for example

(1,4) (2,3) (3,2) (4,1)

Is there any function in R?

+3
source share
3 answers

You can generate your coefficient directly using a function interaction, for example:

R> d <- matrix(1:10, ncol=2)
R> d
     [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    3    8
[4,]    4    9
[5,]    5   10

And then:

R> v <- interaction(d[,1],d[,2], drop=TRUE)
R> v
[1] 1.6  2.7  3.8  4.9  5.10
Levels: 1.6 2.7 3.8 4.9 5.10
R> class(v)
[1] "factor"
+3
source

maybe this is an easy way to concatenate cols into characters:

> d <- matrix(c(1:4,1:4,4:1,4:1), ncol=2)
> factor(apply(d, 1, paste ,collapse=","))
[1] 1,4 2,3 3,2 4,1 1,4 2,3 3,2 4,1
Levels: 1,4 2,3 3,2 4,1
+2
source

Alternatively, you can directly use factor():

> d <- rbind(c(1,3),c(2,3),c(3,2),c(4,1),c(1,3))  
> factor(d[,1]):factor(d[,2])  
[1] 1:3 2:3 3:2 4:1 1:3  
Levels: 1:1 1:2 1:3 2:1 2:2 2:3 3:1 3:2 3:3 4:1 4:2 4:3
+2
source

Source: https://habr.com/ru/post/1792738/


All Articles