Subset of one row element based on the column number vector
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 this particular case, the result should be
result
1 11 21
I tried
resul<-apply(data, 1, [,selectcol])
but it doesn't work
+3
source to share
3 answers
This worked for me with the 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
+1
source to share