【问题标题】:SQL-like query in R or creating a loop?R 中的类似 SQL 的查询或创建循环?
【发布时间】:2017-12-13 08:10:14
【问题描述】:

我的数据集看起来像 that

您可以看到相同的 School-type 出现在同一个社区。 我想看看是否有办法最终得到一个包含变量的数据集:

-学校名称

-total_this year = 同一个社区总和 no_of_grads_this_year

-total_last_year = 同一个社区总和 no_of_grads_last_year

最终目标是创建这两个新列(total_this year、total_last_year)并将它们与学校名称相匹配。所以它看起来像this

我试过的:(说话的方式,这不是一个完整的尝试,因为它是错误的)

temp <- data%>% select(school_name,neighborhood,no_grads_this_year,no_of_grads_last_year)%>% filter(unique(id))%>% mutate()

【问题讨论】:

    标签: sql r dplyr aggregate aggregate-functions


    【解决方案1】:

    这应该会给你想要的输出

    as.data.frame(data %>% group_by (School,Neighbourhood)%>% summarise(sum_this_year= sum(This.Year),sum_last_year = sum(Last.Year)))
    

    【讨论】:

    • 使用 dplyr 和 tidyr 包。
    • 有效!谢谢!您是否推荐一种资源来练习 R 中的此类“查询”?我已经对 dplyr 进行了一些练习,但正如我现在所看到的,我已经偏离了将请求(分组、总结)放在一起的正确方式。
    • 我建议以this 开头,如果您觉得不够,请告诉我。
    【解决方案2】:

    R解决方案:

    df <- data.frame(school = c("A", "A", "B", "B", "B"),
                     neighborhood = c(1,1,2,2,2),
                     no_grads_this_year = c(10,20,40,35,30),
                     no_grads_last_year = c(15,15,80,70,70))
    
    > df
      school neighborhood no_grads_this_year no_grads_last_year
    1      A            1                 10                 15
    2      A            1                 20                 15
    3      B            2                 40                 80
    4      B            2                 35                 70
    5      B            2                 30                 70
    
    df2 <- aggregate(df[,3:4], list(df$school, df$neighborhood), sum)
    names(df2) <- c("School Name", "Neighborhood", "total_this_year", "total_last_year")
    
    > df2
      School Name Neighborhood total_this_year total_last_year
    1           A            1              30              30
    2           B            2             105             220
    

    【讨论】:

    • 它也可以,很好的例子,我也试试。
    猜你喜欢
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多