简体   繁体   中英

R: Selecting a vector of values from a matrix or dataframe with vectors of x and y indices

I am trying to select from a matrix or from a dataframe or a tibble or similar. I can write a function to do what I want, but I wondered if there was something similar built-in.

My function looks like:

matrixselect <- function(m, x, y, r=nrow(m)){ 
   if(! is.matrix(m)){m <- as.matrix(m)} 
   m[x + r * (y - 1)] 
   }  

and if, for example, I want to find c(mydata[1,3], mydata[2,1], mydata[4,3])

mydata <- data.frame(LETTERS[1:4], LETTERS[5:8], LETTERS[9:12])
mydata
#   LETTERS.1.4. LETTERS.5.8. LETTERS.9.12.
# 1            A            E             I
# 2            B            F             J
# 3            C            G             K
# 4            D            H             L
mydata[c(1,2,4), c(3,1,3)]                     # gives more than I want:
#    LETTERS.9.12. LETTERS.1.4. LETTERS.9.12..1
# 1             I            A               I
# 2             J            B               J
# 4             L            D               L
matrixselect(mydata, c(1,2,4), c(3,1,3))       # gives what I want:
# [1] "I" "B" "L"

We can use the row/column index as a matrix by cbind ing

mydata[cbind(c(1, 2, 4), c(3, 1, 3))]
#[1] "I" "B" "L"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM