【发布时间】: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:部分的单行中添加代码来直接设置新变量的名称。
【问题讨论】:
-
好问题,我一直碰到它。而且我还没解决,I defined a new variable