我有一个数据集,我想按评级和州提取餐厅名称。我想编写一个带有两个参数的函数:状态和评级。
> 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 个参数进行提取。
谢谢
最佳答案
可能是这样的:
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
关于r - 提取r中满足2个条件的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33928235/