Let's say I write a function
group=function(x){if (x<=8) {o=1}
else if (x<=11) {o=2}
else o=3;
return(o)}
and have a matrix
test=matrix(1:25,nrow=5); test
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
Now I want to add 3 columns (columns 6, 7 and 8) to the matrix. Column 6 and 7 are the value of the function group
of column 2 and 3, and column 8 is used to mark the change of the group. That is to say, I want to get:
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 6 11 16 21 1 2 12 #6<8 so column 6 is 1, 11<=11 so column 7 is 2; it changes from group 1 to 2, so column 8 is 12
[2,] 2 7 12 17 22 1 3 13
[3,] 3 8 13 18 23 1 3 13
[4,] 4 9 14 19 24 2 3 23
[5,] 5 10 15 20 25 2 3 23
I tried to use
test2=cbind(test,group(test[,2:3]))
but it said the following and didn't work
Warning messages:
1: In if (x == 0) { :
the condition has length > 1 and only the first element will be used
I also tried to use the following, but didn't work either.
test2=cbind(test, apply(test[,2:3],1,group))
So which function should I use? Also, for column 8, do we have such a function? Thank you!
P.S. I was trying to compute a Markov transition matrix using R, not sure if my approach is the most compact way...