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
You can use col
to match the values with selectcol
and subset data
with it.
data[col(data) == selectcol]
# [1] 1 11 21
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With