看起来 select 没有从数据集中删除未选择的列..很奇怪。这是一个简单的例子:
library(nycflights13)
library(dplyr)
dly <- flights %>%
group_by( year, month, day) %>%
summarise(
arr_mean = mean(arr_delay, na.rm=TRUE),
dep_mean = mean(dep_delay, na.rm=TRUE)
) %>% mutate(
dt = as.Date(ISOdate( year, month, day ) )
)
> glimpse( dly, 50 )
Observations: 365
Variables: 6
$ year (int) 2013, 2013, 2013, 2013, 2013...
$ month (int) 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
$ day (int) 1, 2, 3, 4, 5, 6, 7, 8, 9, 1...
$ arr_mean (dbl) 12.6510229, 12.6928879, 5.73...
$ dep_mean (dbl) 11.548926, 13.858824, 10.987...
$ dt (date) 2013-01-01, 2013-01-02, 201...
Run Code Online (Sandbox Code Playgroud)
所以...简单...获取一天的平均值,并添加 R 日期。(是的,我知道数据集中有一个 time_hour,但这应该仍然有效)。现在我想摆脱年、月和日字段(为 ggplot 收集())...但 select 并没有将它们删除:
dly %>% select( dt, arr_mean, dep_mean) %>% glimpse(50)
Observations: 365
Variables: 5
$ year (int) 2013, 2013, 2013, 2013, 2013...
$ month (int) 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
$ dt (date) 2013-01-01, 2013-01-02, 201...
$ arr_mean (dbl) 12.6510229, 12.6928879, 5.73...
$ dep_mean (dbl) 11.548926, 13.858824, 10.987...
Run Code Online (Sandbox Code Playgroud)
日已逝,年月还在。为什么?
即使我嬉戏它们,它们仍然在那里:
dly$year <- NULL
dly$month <- NULL
dly$day <- NULL
dly %>% glimpse(50)
Observations: 365
Variables: 3
$ arr_mean (dbl) 12.6510229, 12.6928879, 5.73...
$ dep_mean (dbl) 11.548926, 13.858824, 10.987...
$ dt (date) 2013-01-01, 2013-01-02, 201...
Run Code Online (Sandbox Code Playgroud)
看起来他们已经消失了,但实际上并没有:
dly %>% select( dep_mean) %>% glimpse(50)
Error: invalid column index : NA for variable: year = year
Run Code Online (Sandbox Code Playgroud)
我确信我错过了一些明显的东西,但我不确定是什么。
如果我不分组/改变数据,它就可以正常工作。
在此先感谢您的帮助
小智 5
如果您运行dly%>%head(),您将在控制台中看到dly仍然分组的:
Groups: year, month [1]
Run Code Online (Sandbox Code Playgroud)
在选择之前插入一个%>% ungroup()%>%应该“free”dly