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

5

我随手想到的一个问题:

让我们来看一下最近一个问题的例子:

数据:

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 )

当前输出: (看一下新变量的长丑名字)

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

好问题,我一直遇到这个问题。而且我还没有解决它,我定义了一个新变量 - Rui Barradas
2个回答

5

我们需要使用cbind,而不是c来生成一个名为'MY_NAME'的一列matrix,而c则会生成一个带有唯一名称(make.unique)的namedvector

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方法中使用cbind的用法。

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))

1
谢谢Akrun,这正是我希望找到的。如果我将来会用它在另一页上:D - Andre Elrico

4

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) 两步走 将这个过程分为两个部分可能更加清晰(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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接