代码之家  ›  专栏  ›  技术社区  ›  Andre Elrico

设置公式中定义的变量的名称

  •  5
  • Andre Elrico  · 技术社区  · 7 年前

    我突然想到这个,

    让我们以最近的一个问题为例:

    数据:

    df1<-
    structure(list(Year = c(2015L, 2015L, 2015L, 2015L, 2016L, 2016L, 
    2016L, 2016L), Category = c("a", "1", "2", "3", "1", "2", "3", 
    "1"), Value = c(2L, 3L, 2L, 1L, 7L, 2L, 1L, 1L)), row.names = c(NA, 
    -8L), class = "data.frame")
    

    代码:

    aggregate( Value ~ Year + c(MY_NAME = c("OneTwo", "three")[Category %in% 1:2 + 1]), data=df1, FUN=sum )
    

    当前输出:(看新var的长而难看的名称)

    #  Year c(MY_NAME = c("OneTwo", "three")[Category %in% 1:2 + 1]) Value
    #1 2015                                                   OneTwo     3
    #2 2016                                                   OneTwo     1
    #3 2015                                                    three     5
    #4 2016                                                    three    10
    

    期望输出:

    #  Year MY_NAME Value
    #1 2015  OneTwo     3
    #2 2016  OneTwo     1
    #3 2015   three     5
    #4 2016   three    10
    

    请注意:

    • 这个问题是关于如何通过将代码添加到 code: 部分。
    2 回复  |  直到 7 年前
        1
  •  5
  •   akrun    7 年前

    而不是 c ,我们需要 cbind ,这将导致 matrix c named vector make.unique )“我的名字”

    aggregate( Value ~ Year +
       cbind(MY_NAME = c("OneTwo", "three")[Category %in% 1:2 + 1]), data=df1, FUN=sum )
    #  Year MY_NAME Value
    #1 2015  OneTwo     3
    #2 2016  OneTwo     1
    #3 2015   three     5
    #4 2016   three    10
    

    在 ?aggregate 在 formula

    公式-一个公式,例如y~x或cbind(y1,y2)~x1+x2,其中 分组x变量(通常是因子)。


    一个带有 tidyverse 会是

    library(dplyr)
    df1 %>% 
          group_by(Year, MY_NAME = c("OneTwo", "three")[Category %in% 1:2 + 1]) %>%
          summarise(Value = sum(Value))
    
        2
  •  4
  •   G. Grothendieck    7 年前

    1) 聚合.data.frame 使用aggregate.data.frame而不是aggregate.formula:

    by <- with(df1, 
      list(
        Year = Year, 
        MY_NAME = c("OneTwo", "three")[Category %in% 1:2 + 1]
      )
    )
    aggregate(df1["Value"], by, FUN = sum)
    

    给:

      Year MY_NAME Value
    1 2015  OneTwo     3
    2 2016  OneTwo     1
    3 2015   three     5
    4 2016   three    10
    

    2) 2步 将其分为两部分(1)创建一个新的数据帧(在其中转换类别)和(2)执行聚合,可能会更简洁一些。

    df2 <- transform(df1, MY_NAME = c("OneTwo", "three")[Category %in% 1:2 + 1])
    aggregate(Value ~ Year + MY_NAME, df2, sum)
    

    (第2a节) 或者用magrittr管道表示(2):

    library(magrittr)
    
    df1 %>%
      transform(MY_NAME = c("OneTwo", "three")[Category %in% 1:2 + 1]) %>%
      aggregate(Value ~ Year + MY_NAME, ., sum)