Select values ​​by factor

I have a data frame that looks something like this:

     a   b   c
1    1   2   3
2    3   4   5
3    4   5   2
4    3   5   6
.....

and I'm trying to make some kind of selection function that will create a vector of values ​​in column a, b or c based on the vector of column names, i.e. for the input vector:

c(a,b,c,b,...)

the output of the selector function should be:

c(1,4,2,5,...)

I can do this by looping through rows of rows or with nested ifelse, but is there a better (more general) way for more than a few columns?

+4
source share
1 answer

We need a row / column index to retrieve values ​​from a dataset i.e.

df1[cbind(1:nrow(df1), match(v1, colnames(df1)))]
#[1] 1 4 2 5

data

v1 <- c('a','b','c','b')
df1 <- structure(list(a = c(1L, 3L, 4L, 3L), b = c(2L, 4L, 5L, 5L), 
c = c(3L, 5L, 2L, 6L)), .Names = c("a", "b", "c"), class = "data.frame", row.names = c("1", 
"2", "3", "4"))
+2
source

Source: https://habr.com/ru/post/1691828/


All Articles