问题
How can i generate this vector in R:
x <- c("R11", "R12", "R13", "R21", "R22", "R23", "R31",....) until R7xx for a set of six letters (R, S, D, A, B, X)?
and so on? Without actually typing it.
回答1:
Try something like this:
m <- expand.grid(c('A','B','D','R','X'),1:7,1:3)
apply(m,1,paste0,collapse = "")
One way to force a specific, non-alphabetic ordering would be to explicitly indicate it using a factor and then order the results from expand.grid:
m <- expand.grid(factor(c('R','A','B','D','X'),levels = c('R','A','B','D','X')),
1:7,
1:3)
m <- m[order(m[,1],m[,2],m[,3]),]
And then run the apply line as before.
回答2:
x <- 10
i<- 0
abc <- array()
xyz <- array()
words <- c('R','S','D','A','B','X')
for(j in 1:6) {
for(i in 1:7) {
abc <- paste(words[j], (x*i + 1):(x*i + 3), sep = "")
xyz <- c(xyz, abc)
}
}
xyz
[1] NA "R11" "R12" "R13" "R21" "R22" "R23" "R31" "R32" "R33" "R41" "R42" "R43" "R51" "R52" "R53"
[17] "R61" "R62" "R63" "R71" "R72" "R73" "S11" "S12" "S13" "S21" "S22" "S23" "S31" "S32" "S33" "S41"
[33] "S42" "S43" "S51" "S52" "S53" "S61" "S62" "S63" "S71" "S72" "S73" "D11" "D12" "D13" "D21" "D22"
[49] "D23" "D31" "D32" "D33" "D41" "D42" "D43" "D51" "D52" "D53" "D61" "D62" "D63" "D71" "D72" "D73"
[65] "A11" "A12" "A13" "A21" "A22" "A23" "A31" "A32" "A33" "A41" "A42" "A43" "A51" "A52" "A53" "A61"
[81]"A62" "A63" "A71" "A72" "A73" "B11" "B12" "B13" "B21" "B22" "B23" "B31" "B32" "B33" "B41" "B42"
[97] "B43" "B51" "B52" "B53" "B61" "B62" "B63" "B71" "B72" "B73" "X11" "X12" "X13" "X21" "X22" "X23"
[113] "X31" "X32" "X33" "X41" "X42" "X43" "X51" "X52" "X53" "X61" "X62" "X63" "X71" "X72" "X73"
NA gets generated as first value. To remove that NA you can use,
xyz <- xyz[-1]
来源:https://stackoverflow.com/questions/32567751/generating-strings-combining-letter-and-number-sequences-in-r