Reputation: 3587
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
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
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
Reputation: 366
what if you try
selection <- cbind(1:3, selectcol)
result <- data[sel]
Upvotes: 5