I have a matrix of dim(37,18)
. My aim is to get the first column and convert it into a factor with thre levels.
This is what I did :
> YY <- ND[,1] # ND is the matrix
> class(YY)
[1] "character"
> YY <- as.factor(YY)
> class(YY)
[1] "factor"
the output I get:
> YY
V2 V3 V4 V5 V6 V7 V8 V9 V10 V2 V3 V4 V5 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 V21 V22
S1 S2 S3 S4 S5 S6 S7 S8 S9 A1 A2 A3 A4 E1 E2 E3 E4 E5 E6 E7 E8 E9 E10 E11 E12 E13 E14 E15 E16 E17 E18 E19 E20 E21
V23 V24 V25
E22 E23 E24
37 Levels: A1 A2 A3 A4 E1 E10 E11 E12 E13 E14 E15 E16 E17 E18 E19 E2 E20 E21 E22 E23 E24 E3 E4 E5 E6 E7 E8 E9 S1 S2 S3 S4 S5 S6 S7 ... S9
I want the output as:
> y
[1] S S S S S S S S S A A A A E E E E E E E E E E E E E E E E E E E E E E E E
Levels: A E S
We can use sub
to remove the numbers
y <- factor(sub("\\d+", "", YY))
y
#[1] S S S S S S S S S A A A A E E E E E E E E E E E E E E E E E E E E E E E E
#Levels: A E S
YY <- structure(c(29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L, 37L, 1L,
2L, 3L, 4L, 5L, 16L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 6L, 7L,
8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 17L, 18L, 19L, 20L, 21L
), .Names = c("V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9",
"V10", "V2", "V3", "V4", "V5", "V2", "V3", "V4", "V5", "V6",
"V7", "V8", "V9", "V10", "V11", "V12", "V13", "V14", "V15", "V16",
"V17", "V18", "V19", "V20", "V21", "V22", "V23", "V24", "V25"
), .Label = c("A1", "A2", "A3", "A4", "E1", "E10", "E11", "E12",
"E13", "E14", "E15", "E16", "E17", "E18", "E19", "E2", "E20",
"E21", "E22", "E23", "E24", "E3", "E4", "E5", "E6", "E7", "E8",
"E9", "S1", "S2", "S3", "S4", "S5", "S6", "S7", "S8", "S9"), class = "factor")