hbelbo
hbelbo

Reputation: 197

Pull values from a data frame by using indexing vectors for both row and column?

I'm out for a better method for pulling values from data frame by using indexing vectors both for rows and columns. The example below works fine, but I suppose there are more efficient methods using some kind of sapply or purr::map trick?

df <- data.frame(a = c("a1","a2", "a3", "a4"), b= c("b1","b2", "b3", "b4"), stringsAsFactors = F)
col_selector <- sample(as.integer(c(1,2)), size = 10, replace = T)
row_selector <- sample(as.integer(c(1:4)), size = 10, replace = T)

v = character()
for (i in seq_along(col_selector)) {
  v = c(v, df[row_selector[i], col_selector[i]])
} 
print(v)
[1] "a4" "a3" "a4" "a2" "a3" "a1" "b1" "b1" "b3" "b1"

Upvotes: 2

Views: 38

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101024

Personally I think the answer by @akrun is most elegant approach. Here is another base R solution, using mapply

v <- mapply(function(x,y) df[x,y], row_selector,col_selector)

Upvotes: 2

akrun
akrun

Reputation: 886938

We can use cbind to create a matrix of row/column index and use that to extract the elements from the dataset

v2 <- df[cbind(row_selector, col_selector)]
identical(v, v2)
#[1] TRUE

Upvotes: 2

Related Questions