Select multiple values from a dataframe using a matrix with indices
I have a for loop, which returns me values from one dataframe using which, which.min and which.max giving me the "coordinates". Here an example
df <- as.data.frame(matrix(rnorm(11284), nrow=403, ncol=28))
row <- matrix(data=c(1:403),nrow=403, ncol=1)
col <- matrix(rnorm(403,14,3), nrow=403, ncol=1)
col <- round(col, 0)
coord <- cbind(row, col)
Coord holds the coordinates for a criterium that I have defined before. I now want to extract the respective values according to those c开发者_开发问答oordinates from df with a for loop
for (i in 1:nrow(coord)) {
print(df[coord[i,1], coord[i,2]])
}
When I use
output <- df[coord[i,1], coord[i,2]])
it only gives me the last expression of the loop. My simple question is now: How do I store not only the last expression from this loop, but the whole vector that is given me by print?
You're surprised? You store every loop only that one value of the loop in output. So after the last loop it's only the last value. The correct loop solution would be :
output <- vector(length=nrow(coord))
for (i in 1:nrow(coord)){
output[i] <- df[coord[i,1],coord[i,2]]
}
But you don't have to use a loop. Given you have the coordinates in a dataframe or matrix, this can be done a whole lot simpler anyway :
output <- Df[coord]
No loop needed.
This sounds a bit like OP used SAS before, in R variables have no history. Instead of line-by-line operation in R people try to do vector-based calculation and use apply
to apply a function to every entry in a vector or matrix. In more conditional cases you can use a for-loop and store the return-values as entries within it and then return or print them all at once:
my <- function() {
outputs <- rep(0,20)
for(i in 1:20) {
outputs[i] <- i*i
}
return(outputs)
}
精彩评论