我想重命名在dplyr中使用group_by创建的列。创建的名称是format(date2, "%Y-%m")
,不是很有用。我尝试过几件事。我希望新名称是" yrMth"
df <- data.frame(Person = c(rep("abc",3), rep("eee", 5)),
date = c("4/1/2016", "4/3/2016", "4/12/2016", "5/3/2016", "5/4/2016","5/10/2016","5/6/2016", "5/11/2016"),
account = c("123","123","123","222","222","333","222","333"), stringsAsFactors = F)
df$date2 <- mdy(df$date)
df %>%
group_by(format(date2, "%Y-%m"))
Person date account date2 `format(date2, "%Y-%m")`
<chr> <chr> <chr> <date> <chr>
1 abc 4/1/2016 123 2016-04-01 2016-04
2 abc 4/3/2016 123 2016-04-03 2016-04
3 abc 4/12/2016 123 2016-04-12 2016-04
4 eee 5/3/2016 222 2016-05-03 2016-05
5 eee 5/4/2016 222 2016-05-04 2016-05
6 eee 5/10/2016 333 2016-05-10 2016-05
7 eee 5/6/2016 222 2016-05-06 2016-05
8 eee 5/11/2016 333 2016-05-11 2016-05
以下代码不起作用,任何想法。
df %>%
mutate( yrMth = group_by(format(date2, "%Y-%m")))
df %>%
rename( yrMth = group_by(format(date2, "%Y-%m")))
答案 0 :(得分:1)
df<- group_by(df, date2) %>% mutate(yrMth = format(date2, "%Y-%m"))
这对我来说非常好
但是如果你想在不创建任何新列的情况下这样做,你可以使用以下功能:
df<- mutate_at(df, vars(date), function(x){x = format(x, "%Y-%m"); return(x)})
答案 1 :(得分:0)
无需使用mutate
或rename
。如eipi10的评论所述,只需执行以下操作即可轻松实现:
df %>%
group_by(yrMth = format(date2, "%Y-%m"))
如果要动态命名变量,则可以选择以下方式:
name <- "yrMth2"
df %>%
group_by(!!name := get(format(date2, "%Y-%m")) )
答案 2 :(得分:0)
我知道这个答案有点晚了,但是在 dplyr_1.0.2
中,您可以在调用 group_by
时简单地设置分组变量名称的名称:
df <- data.frame(Person = c(rep("abc",3), rep("eee", 5)),
date = c("4/1/2016", "4/3/2016", "4/12/2016", "5/3/2016", "5/4/2016","5/10/2016","5/6/2016", "5/11/2016"),
account = c("123","123","123","222","222","333","222","333"), stringsAsFactors = F)
df$date2 <- mdy(df$date)
df %>% group_by("yrMth" = format(date2, "%Y-%m"))