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

烈酒焚心 提交于 2019-12-23 21:24:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!