【问题标题】:Extracting value that meets 2 conditions in r在r中提取满足2个条件的值
【发布时间】:2015-11-25 23:30:49
【问题描述】:

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

> 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 个参数提取。

谢谢

【问题讨论】:

    标签: r


    【解决方案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

    【讨论】:

    • 如果只有 1 个小数点的特异性,将评级存储为字符或因子数据甚至可能是有意义的。这将避免需要处理数值精度公差。
    • 是的,这是真的。我实际上是想将其发布为我的初始答案,但后来我决定使用almost.equal(作为通用选项)可能会更好。非常有效的评论,谢谢@thelatemail
    • 或者将其存储为 0 到 50 之间的整数,并确保所有比较都是整数到整数。
    • 这是另一个很好的@thelatemail,它肯定会工作,谢谢。明天我会写下来,我几乎睁不开眼睛。英国凌晨 1 点:P
    • @LyzanderR 感谢您在 cmets 中如此彻底地解释,这确实有道理。我不知道这个功能。学到了新东西。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2018-03-02
    相关资源
    最近更新 更多