Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 coordinates 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?

like image 980
Sketch Avatar asked Aug 12 '26 21:08

Sketch


1 Answers

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.

like image 105
Joris Meys Avatar answered Aug 15 '26 11:08

Joris Meys



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!