我无法理解下面R脚本中出现的问题。在调用fct_expand之前定义变量级别会导致编译成功,但是当我将定义直接插入fct_expand时,R会产生错误
“mutate_impl(.data,dots)中的错误:尝试应用非函数”
R-script复制错误(Microsoft R open 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。)。所以它必须依赖于我猜的一些设置。以下示例说明了同样的问题;在上面给出错误的机器上的代码如下:
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