【问题标题】:Set name of variable defined in formula设置公式中定义的变量名称
【发布时间】:2018-10-25 14:48:14
【问题描述】:

这只是突然出现在我的脑海中,

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

数据:

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:部分的单行中添加代码来直接设置新变量的名称。

【问题讨论】:

标签: r formula


【解决方案1】:

我们需要cbind,而不是c,这会导致matrix 的列名称为“MY_NAME”,而c 得到一个named vector,其名称是唯一的(make.unique ) 的“MY_NAME”

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中提到了cbindformula方法中的用法

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


tidyverse 的选项是

library(dplyr)
df1 %>% 
      group_by(Year, MY_NAME = c("OneTwo", "three")[Category %in% 1:2 + 1]) %>%
      summarise(Value = sum(Value))

【讨论】:

  • 感谢 akrun,这正是我希望找到的。如果我会在另一个页面上使用它:D
【解决方案2】:

1) aggregate.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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 2013-10-08
    相关资源
    最近更新 更多