R.P. Tamil Selvan
R.P. Tamil Selvan

Reputation: 43

extracting value of variable from dataframe

I have one issue in selecting a value of one variable conditional on the value of another variable in a dataframe.

Dilutionfactor=c(1,3,9,27,80)
Log10Dilutionfactor=log10(Dilutionfactor)
Protection=c(100,81.25,40,10.52,0)
RM=as.data.frame(cbind(Dilutionfactor,Log10Dilutionfactor,Protection))

Now i want to know the value of Log10Dilutionfactor condition on the value of Protection is equal to either 50 (if it appear) or the value immediately just below 50. when i used subset(RM,Protection<= 50)it gives three rows and when I tried RM[grepl(RM$Protection<=50,Log10Dilutionfactor),] it gives 0 values with warning message. I really appreciate if someone help me.

Upvotes: 1

Views: 65

Answers (3)

Erdem Akkas
Erdem Akkas

Reputation: 2060

You can use 2 subset:

subset(RM,Protection==max(subset(RM,Protection<= 50)$Protection))$Log10Dilutionfactor
# [1] 0.954243

Upvotes: 1

Larusson
Larusson

Reputation: 267

or find the index value of protection that is closest to 50

 index = which(abs(RM$Protection-50)<=min(abs(RM$Protection-50)))

and then look it up in what ever column you want. e.g for Dilutionfactor

 RM$Dilutionfactor[index]

Upvotes: 1

ikop
ikop

Reputation: 1790

You could use

with(RM, Log10Dilutionfactor[which(Protection == max(Protection[Protection <= 50]))])
# [1] 0.9542425

Upvotes: 1

Related Questions