问题
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
回答1:
You can use col
to match the values with selectcol
and subset data
with it.
data[col(data) == selectcol]
# [1] 1 11 21
回答2:
what if you try
selection <- cbind(1:3, selectcol)
result <- data[sel]
回答3:
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
来源:https://stackoverflow.com/questions/26705570/subset-one-element-of-a-row-based-on-vector-of-column-number