Select column from data frame based on dynamic value in R -


i've been banging head against problem , feel there must efficient way in r doesn't involve writing loop. suggestions appreciated!

i'd create new column in data frame contains values existing columns in dataframe, column value selected dynamically specified. example clarify:

> mydata <- head(mtcars) > mydata                    mpg cyl disp  hp drat    wt  qsec vs gear carb mazda rx4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4 mazda rx4 wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4 datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1 hornet 4 drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1 hornet sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2 valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1 > myquery <- c("cyl","cyl","gear","gear","carb", "carb") 

at point, i'd know if there's simple r function select value of column myquery each row of mydata, in other words:

f(mydata, myquery) 6 6 4 3 2 1 

thanks in advance if knows of simple , efficient version way write f, in advance time.

you can index data.frame matrix achieve behavior

dd<-head(mtcars) myquery <- c("cyl","cyl","gear","gear","carb", "carb") dd[cbind(seq_along(myquery), match(myquery, names(dd)))] # [1] 6 6 4 3 2 1 

the first column of matrix row, second column (and note when using method there no comma in brackets when normal [,] subset. here converted myqeury values numeric column indices using match both columns of matrix same type (as have be). have used character matrix if used row names index rows. thus

dd[cbind(rownames(dd), myquery)] # [1] 6 6 4 3 2 1 

also works.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -