Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

subset

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

like image 527
ulrich Avatar asked Sep 01 '25 10:09

ulrich


1 Answers

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

data[col(data) == selectcol]
# [1]  1 11 21
like image 75
Rich Scriven Avatar answered Sep 03 '25 00:09

Rich Scriven