我有一个数据集,我想通过评级和状态提取餐馆名称。我想用两个参数编写一个函数:state和rating。
> 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个参数进行提取。
谢谢
答案 0 :(得分: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
中偷走了almost.equal