2

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.

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Why are you doing t(rbind()) and not just cbind()? Also, sticking with the presence of row.names you could just use M[cbind(match(names(myNamedNum), rownames(M)), myNamedNum)].
cbind()! Good catch.
0

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])]
}

1 Comment

You don't need a for loop here. You can just use matrix indexing. Create a matrix to subset from where the first column is the rows you want, and the second is the columns you want. Since you are dealing with rownames, you can use match to get the position of the row. A complete example would be: M[cbind(match(names(myNamedNum), rownames(M)), myNamedNum)]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.