ulrich
ulrich

Reputation: 3587

Subset one element of a row based on vector of column number

I have a dataset

data <- cbind(c(1,2,3),c(1,11,21))

I want to extract one element from each row based on the column number given by a vector

selectcol <- c(1,2,2)

In that particular case the result should be

result

1
11
21

I have tried

resul<-apply(data, 1, [,selectcol])

but it does not work

Upvotes: 4

Views: 599

Answers (3)

Rich Scriven
Rich Scriven

Reputation: 99331

You can use col to match the values with selectcol and subset data with it.

data[col(data) == selectcol]
# [1]  1 11 21

Upvotes: 5

LyzandeR
LyzandeR

Reputation: 37879

This worked for me using a function:

data <- data.frame(cbind(c(1,2,3),c(1,11,21)))

selectcol <- c(1,2,2)

elems<-vector()
extract_elems <- function(data, selectcol) {
  for ( i in 1:length(selectcol)) {
    elems <- append(elems,data[i,selectcol[i]])
  }
  return(elems)
}

output <- extract_elems(data,selectcol)

> output
[1]  1 11 21

Upvotes: 1

Martijn vd Voort
Martijn vd Voort

Reputation: 366

what if you try

 selection <- cbind(1:3, selectcol)
 result <- data[sel]

Upvotes: 5

Related Questions