I’m really a beginner in R so, sorry if my code shocks you guys.
My data resembles something like this:
a b c d e f g h i j
t1 0 0 0 0 3 0 0 0 0 0
t2 0 0 0 0 0 6 0 0 0 0
t3 0 0 0 0 0 0 0 0 0 8
t4 0 0 0 0 0 0 0 0 9 0
I’d like to, for each row find the column with the maximum value and then get columns minus 3 to plus 3 of that one.
I wrote the following script to perform exactly that:
M<-c(1)
for (row in 1: length(D[,1])) {
max<-which.max(D[row,])
D<-D[,c(max-3,max-2,max-1,max,max+1,max+2,max+3)]
M<- cbind(M,D)
}
M<-M[,-1]
It would work, except for the case in which the maximum value is in a column near the beginning or end of a row (like rows t3 and t4 in the example above). In this case I’d like to have the 7 columns more close to the column with the maximum value, like this:
t1 0 0 0 3 0 0 0
t2 0 0 0 6 0 0 0
t3 0 0 0 0 0 0 8
t4 0 0 0 0 0 9 0
Help would be really appreciated!
dput() version of example data:
structure(list(a = c(0L, 0L, 0L, 0L), b = c(0L, 0L, 0L, 0L),
c = c(0L, 0L, 0L, 0L), d = c(0L, 0L, 0L, 0L), e = c(3L, 0L,
0L, 0L), f = c(0L, 6L, 0L, 0L), g = c(0L, 0L, 0L, 0L), h = c(0L,
0L, 0L, 0L), i = c(0L, 0L, 0L, 9L), j = c(0L, 0L, 8L, 0L)), .Names = c("a",
"b", "c", "d", "e", "f", "g", "h", "i", "j"), class = "data.frame",
row.names = c("t1", "t2", "t3", "t4"))
This should work nicely:
To test that the key column-selecting bit works as you’d like it to, you can try the following: