r - 提取r中满足2个条件的值

标签 r

我有一个数据集,我想按评级和州提取餐厅名称。我想编写一个带有两个参数的函数:状态和评级。

> 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/

相关文章:

R/ Shiny : Plotly reactive height discarded after window resize

r - ggplot : how to assign both color and shape for one factor, 以及另一个因素的形状?

r - 使用 Shiny 的包上传数据、更改数据框和下载结果

r - 使用 get() 来引用带有 R 的 quantmod 数组中的列?

c++ - rep(x, each=3) 相当于 Armadillo

r - 有没有一种快速计算多列乘法结果的方法,但根据 NA 值具有不同的比例?

R:如何在包meta的metaprop中指定置信区间

r - 如何在不加载内存文件的情况下以像素为单位获取图像宽度和高度

R数据帧: Time efficient way to transform data

r - 从 github 安装 ggbiplot