【问题标题】:Select rows from Data Frame based on listed values in R Programming根据 R 编程中列出的值从数据框中选择行
【发布时间】:2021-03-20 22:28:55
【问题描述】:

我正在使用 R 编程对体育数据进行探索性数据分析... 我想根据两个条件从数据框中打印记录 条件 : Country == "England" ||(OR 运算符) Ground == ground 可以是以下列表中的任何一个

List = c("Birmingham" ,"Bristol" ,"Cardiff" ,"Chester-le-Street" , 
              "Leeds" ,"East London" ,"Lord's", "The Oval",
              "Manchester" ,"Nottingham" ,"Southampton" ,"Taunton")

样本数据(提供的简图)

data.frame(
  Ground = c('Hambantota', 'Benoni', 'Benoni', 'Hambantota', 'Hambantota',
             'Pallekele', 'Pallekele'),
  Country = c('Bangladesh', 'SouthAfrica', 'Pakistan', 'SriLanka', 'Bangladesh',
              'SriLanka', 'Bangladesh')
)

我正在尝试...

subset(WC_Grounds,WC_Grounds$Country=="England"||WC_Grounds %in% WC_Grounds_List)

但它返回 0 条记录

【问题讨论】:

  • 为了让我们帮助您,请编辑您的问题以包含reproducible example。例如,要生成最小数据集,您可以使用head()subset() 或索引。然后使用dput() 给我们一些可以立即放入R 的东西。另外,请确保您知道该怎么做when someone answers your question。更多信息可以在 StackOverflow 的help center 找到。谢谢!
  • 感谢您的评论,但我在图片下方发布了我正在做的事情,但它不起作用。我正在尝试使用子集(WC_Grounds,WC_Grounds$Country=="England"||WC_Grounds %in% WC_Grounds_List) 如果您知道如何使用 head() 或 dput() 请回答
  • 我想要新的数据框,其中仅包括国家作为英格兰或理由 %in% 列表
  • 我们不是您的客户。我们不为你工作。作为提问者,您有责任让我们这些花时间自愿帮助您的用户更容易。也就是说,请实际阅读我提供的链接并编辑您的问题以包含可重现的示例。
  • 通过您发布您的数据图像,您迫使我们手动复制您的数据。请删除图像并将其替换为可重现的示例。您可以通过单击并阅读我的第一条评论中的可重现示例链接来准确了解如何做到这一点。

标签: r data-visualization data-analysis


【解决方案1】:

subset(WC_Grounds, WC_Grounds$Country=="England" | WC_Grounds$Ground %in% WC_Grounds_List)

为你工作?

||和 && - 这些运算符是“短路的”:只要 ||看到第一个 TRUE 它返回 TRUE 而不计算任何其他内容。您应该改用|,它是矢量化的,因此适用于数据集中的多个值。

这是一个使用我在您的问题中添加的简短示例数据的示例:

WC_Grounds <- data.frame(
  Ground = c('Hambantota', 'Benoni', 'Benoni', 'Hambantota', 'Hambantota',
             'Pallekele', 'Pallekele'),
  Country = c('Bangladesh', 'SouthAfrica', 'Pakistan', 'SriLanka', 'Bangladesh',
              'SriLanka', 'Bangladesh')
)

List = c('Hambantota', 'Benoni')

subset(WC_Grounds, WC_Grounds$Country == "SriLanka" | WC_Grounds$Ground %in% List)

#>       Ground     Country
#> 1 Hambantota  Bangladesh
#> 2     Benoni SouthAfrica
#> 3     Benoni    Pakistan
#> 4 Hambantota    SriLanka
#> 5 Hambantota  Bangladesh
#> 6  Pallekele    SriLanka

reprex package (v1.0.0) 于 2021-03-20 创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 2021-08-23
    • 2018-11-06
    相关资源
    最近更新 更多