2015-11-25 21 views
2

我有一個數據集,我想按評分和狀態提取餐館名稱。我想寫一個帶有兩個參數的函數:狀態和評級。在r中提取符合2個條件的值

> rest_data 
    restaurant_name rating state visitors_per_day 
1   a  3.4 NY   34 
2   b  5.0 CA   20 
3   c  4.0 NY   11 
4   d  4.3 AZ   34 
5   e  4.9 NY   14 
6   f  3.0 CA   21 

這是我應該如何調用該函數: 狀態名稱和等級

my_function("NY", 4.9) 

我想盡各種辦法,但我只能使用1個參數提取。

謝謝

回答

3

事情是這樣的,也許:

get_rest <- function(state, rating) { 
    rest_data[rest_data$state == state & rest_data$rating == rating, 'restaurant_name'] 
} 

get_rest('NY', 4.9) 
#[1] e 

而實際上這是一種更好的方法來測試它:

#almost equal is a vectorised form of all.equal that 
#checks if two numbers are equal but with a tolerance level 
#because of the inconistenies of storing numbers in a computer 
#check: http://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal 
#for details 
almost.equal <- function (x, y, tolerance=.Machine$double.eps^0.5, 
          na.value=TRUE) 
{ 
    answer <- rep(na.value, length(x)) 
    test <- !is.na(x) 
    answer[test] <- abs(x[test] - y) < tolerance 
    answer 
} 

get_rest <- function(state, rating) { 
    rest_data[rest_data$state == state & almost.equal(rest_data$rating, rating), 
      'restaurant_name'] 
} 

get_rest('NY', 4.9) 
#[1] e 

我從here

+0

被盜almost.equal將評分存儲爲字符或事實可能更有意義r數據,如果只有1個小數點的特異性。這將避免使用數字精度公差來解決問題。 – thelatemail

+0

是的,這是非常真實的。我實際上是想把這張貼作爲我的初步答案,但後來我決定使用'almost.equal'(作爲一個通用選項)可能會更好。非常有效的評論,感謝@thelatemail – LyzandeR

+0

或者就此而言,將其存儲爲0到50之間的整數,並確保所有比較都是整數到整數。 – thelatemail