Reputation: 809
In R, say you have a named numeric such as:
3777 3727 3421 2373 3259 512 3174 3456 3536 805
4 4 8 9 2 2 6 4 6 6
The values on the top are rownames from a larger matrix, and the values below it are the column of data I want from that row.
So, I want from dataframe (or matrix) row with name 3777, col 4's value. and so on.
What is the easiest way to do this?
thank you.
Upvotes: 2
Views: 69
Reputation: 54340
Can you use row index instead of row names? If so, you don't need a loop:
a <- rnorm(10000)
M <- matrix(a,nrow=100)
c1 <- c(1,3,4,5,9) #3777 3727 3421 2373 3259 512 3174 3456 3536 805
c2 <- c(3,8,10,11,23) # 4 4 8 9 2 2 6 4 6 6
M[cbind(c1,c2)]
# [1] -0.8216866 0.5427404 0.4462874 -0.6547175 -1.6598367
Upvotes: 2
Reputation: 809
The way I did it is:
myMatrix #any matrix
myNamedNum #from above example
for (i in 1:length(myNamedNum)){
myMatrix[names(myNamedNum[i]),as.numeric(myNamedNum[i])]
}
Upvotes: 0