【问题标题】:How to create a function that calculates and retrieves a value from a table?如何创建一个从表中计算和检索值的函数?
【发布时间】:2017-06-26 12:20:31
【问题描述】:

我有一张表格,其中包含有关驾驶员违规和违规价值的信息。我有两列 Value (of infraction) 和 year (of infraction)。对于每一年的违规行为,我都有几个值。年份从 2000 年到 2014 年。

我需要一个可以检索每个“预定”年份的违规总数的函数。即,当用户键入年份时,仅获取该年份的信息。到目前为止,我只能设法同时获取所有年份的信息

我试过了:

total_year <- function(x=infractions$year){
  aggregate(infractions$value ~ infractions$year_deb, FUN=sum, na.rm = TRUE)
}

然后我输入

total_year(2012)

我得到了一张列出所有年份的违规行为表,但我只想要 2012 年的总数。

我的桌子是这样的:

       value year 
375714  1,00 2011 
375715  0,00 2012 
375716  0,00 2013 
375717  0,00 2014 
375738 12,00 2011 
375739  7,00 2012 
375740  2,00 2013 
375741  4,00 2014 
375762 23,00 2011 
375763 14,00 2012 
375764 18,00 2013 
375765  7,00 2014 
375786  6,00 2011 
375787  4,00 2012 
375788  2,00 2013 
375789  5,00 2014 
375810  0,00 2011 
375811  0,00 2012 
375812  0,00 2013

【问题讨论】:

  • 您想了解那一年的违规总数 number 吗?还是那一年的违规清单?此外,如果您可以提供一个可重现的示例(请参阅here)供其他人使用,您将有更多的运气得到答案(并很快得到答案)
  • 是的,当年的违规总数。即:年度(2012 年)违规总数,谢谢。我将尝试重现该示例
  • 值年375714 1,00 2011 375715 0,00 2014 375717 0,00 2014 375738 2014 375738 12,00 2011 375739 7,00 2012 2014 375740 2,00 2014 2014 2011年375763 14,00 2014 375786 6,00 2012 375788 2,00 2014 375789 5,00 2014 375810 0,00 2012 2012年375811 0,00 2012 375812 0,00 2013
  • 格式化文本和代码,将数据从评论移到 Q,改写标题

标签: r function


【解决方案1】:

这是另一个使用dplyr的解决方案

数据

set.seed(123)

df <- data.frame(value = sample(c("speeding", "parking", "dui"), 45, replace = T),
                 year = rep(2000:2014, 3))

功能

library(dplyr)

total_year <- function(data, x) {
  data %>%
    filter(year == x) %>%
    group_by(year) %>%
    summarize(inf = length(unique(value))) %>%
    ungroup
}

用法

total_year(df, 2014)
#     year   inf
#     <int> <int>
#   1  2014     1

【讨论】:

  • 很高兴它有帮助。如果您发现某个答案有帮助,请务必在旁边点赞。
猜你喜欢
  • 2022-01-09
  • 2014-11-05
  • 2020-03-30
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多