我无法理解下面的 R 脚本中出了什么问题。在调用 fct_expand 之前定义变量级别会导致编译成功,但是当我将定义直接插入 fct_expand 时,R 会产生错误
“mutate_impl(.data, dots) 中的错误:尝试应用非函数”
复制错误的 R 脚本(Microsoft R 打开 3.4.0.0 和 R 3.3.3):
library(dplyr)
library(forcats)
library(magrittr)
f <- factor(1:3)%>% tbl_df
f_lev <- factor(1:6) %>% tbl_df
#This compiles just fine
levels <- f_lev %$% value %>% levels
f %>% mutate(value = fct_expand(value, levels)) %$% value %>% levels
#This wont compile
f %>% mutate(value = fct_expand(value, f_lev %$% value %>% levels)) %$% value %>% levels
编辑:代码不会在尝试运行 R 3.3.3 的 4 台机器中的 3 台上运行(没有错误的计算机从未安装过 RTVS 或 Microsoft R open。)。所以它必须依赖于我猜的一些设置。下面的例子说明了同样的问题;在上面给出以下代码错误的机器上:
library(dplyr)
library(forcats)
library(magrittr)
f <- factor(1:3) %>% tbl_df
f_lev <- factor(1:6) %>% tbl_df
f %>% {
tmp <- f_lev %$% value %>% levels
mutate(., value = fct_expand(value, tmp))
} %>% str
f %>% {
mutate(., value = fct_expand(value, f_lev %$% value %>% levels))
} %>% str
产生两种不同的结果:
Classes 'tbl_df', 'tbl' and 'data.frame': 3 obs. of 1 variable:
$ value: Factor w/ 6 levels "1","2","3","4",..: 1 2 3
Classes 'tbl_df', 'tbl' and 'data.frame': 3 obs. of 1 variable:
$ value: Factor w/ 3 levels "1","2","3": 1 2 3
在没有给出编译错误的计算机上,后一个代码会导致:
Classes 'tbl_df', 'tbl' and 'data.frame': 3 obs. of 1 variable:
$ value: Factor w/ 6 levels "1","2","3","4",..: 1 2 3
Classes 'tbl_df', 'tbl' and 'data.frame': 3 obs. of 1 variable:
$ value: Factor w/ 6 levels "1","2","3","4",..: 1 2 3