Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put a variable into an object in R

Tags:

r

Sorry about the title. I'm actually having a hard time figuring out how to even phrase the question, which is why I can't just google it.

I want to get information from a data frame in R using a variable as the column title.

test = data.frame(season=c('winter','summer'), temp=c('cold','hot'))
what.season = 'winter'
test$what.season

The third line obviously doesn't work, but what I am trying to pass it is the value of what.season so that it reads test$winter and returns 'cold'

Edit for future readers: I'm tired and I phrased it wrong, but the correct answer got at what I was trying to do.

like image 335
Brian Jackson Avatar asked Dec 05 '25 03:12

Brian Jackson


2 Answers

Here is how I would do it

test[test$season == "winter", ]$temp

The $ operator at the end selects to column of interest while the logical operator == selects the row of interest

like image 172
Stedy Avatar answered Dec 07 '25 19:12

Stedy


You can also use subset function

> subset(test, season==what.season, select=temp)
  temp
1 cold
like image 31
Jilber Urbina Avatar answered Dec 07 '25 18:12

Jilber Urbina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!