为什么 is.double() returns 是因子变量?

Why is.double() returns a factor variable?

is.double()函数returns一个factor变量。这是代码及其输出:

df <- data.frame(City = c("A","B","A","C","A","B"), 
Empl = c(3,6,3,2,6,8), UnEmpl = c(4,7,5,6,3,1))

select_if(df, is.double)

这就是我们得到的,返回所有double个变量:

Empl UnEmpl
<dbl> <dbl>
3   4           
6   7           
3   5           
2   6           
6   3           
8   1   

一些操作后

df <- df %>% group_by(City) %>% mutate(total = sum(Empl,UnEmpl))
select_if(df, is.double)

这就是我们得到的,city 是一个 factor 变量但仍然由函数 is.double()

返回
City    Empl  UnEmpl total
<fctr>  <dbl> <dbl>  <dbl>
A   3   4   24  
B   6   7   22  
A   3   5   24  
C   2   6   8   
A   6   3   24  
B   8   1   22

更新

select_if() 的文档明确表示始终保留分组变量。您还可以查看 dplyr 作者的 this Github page。最终,将新的 dfungroup() 取消组合就可以了。

library(dplyr)
df <- data.frame(City = c("A","B","A","C","A","B"), 
                 Empl = c(3,6,3,2,6,8), 
                 UnEmpl = c(4,7,5,6,3,1))

select_if(df, is.double)

> select_if(df, is.double)
  Empl UnEmpl
1    3      4
2    6      7
3    3      5
4    2      6
5    6      3
6    8      1

df <- df %>% 
  group_by(City) %>% 
  mutate(total = sum(Empl,UnEmpl))

> select_if(ungroup(df), is.double)
  Empl UnEmpl total
1    3      4    24
2    6      7    22
3    3      5    24
4    2      6     8
5    6      3    24
6    8      1    22

总而言之,您观察到的是预期的行为。