【发布时间】:2017-11-30 13:44:52
【问题描述】:
我有以下情况:我有一个 tibble 和一个包含一些所述 tibbles 列名的字符向量。现在我使用dplyr::mutate_if 将这些列设置为0,其名称包含在字符向量中。我通过提供一个逻辑向量作为谓词来做到这一点。
到目前为止,这已经奏效了:
library(tidyverse)
test_OK <-
tribble(~"Var1", ~"Var2", ~"Var3",
11, 12, 13,
21, 22, 23,
31, 32, 33)
vars_to_change_OK <- c("Var1", "Var3")
## Everything works out
test_OK %>% mutate_if(names(.) %in% vars_to_change_OK, funs(. * 0))
但现在我发现列名中有空格和数字,但过程失败了:
test_FAIL <-
tribble(~"Var 1", ~"Var 2", ~"Var 3",
11, 12, 13,
21, 22, 23,
31, 32, 33)
vars_to_change_FAIL <- c("Var 1", "Var 3")
## Error [...] unexpected numeric constant
test_FAIL %>% mutate_if(names(.) %in% vars_to_change_FAIL, funs(. * 0))
请注意,唯一的区别是列名从 Var[0-9] 更改为 Var [0-9]。
我想知道这是否是dplyr 中的一个错误,或者我是否一直在无意中使用mutate_if 函数。此外,我对错误发生的方式和原因感兴趣。提前感谢您提供任何见解!
PS.:我知道有一个简单的基本 R 解决方法,如下所示:
###############################
## workaround in base R:
test_FAIL[, match(vars_to_change_FAIL, names(test_FAIL))] <- 0
test_FAIL
不过,我对为什么上述方法在 dplyr 中不起作用很感兴趣。
更新:我添加了我的sessionInfo(),以防版本很重要:
R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
Matrix products: default
locale:
[1] LC_COLLATE=German_Germany.1252 LC_CTYPE=German_Germany.1252 LC_MONETARY=German_Germany.1252
[4] LC_NUMERIC=C LC_TIME=German_Germany.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] dplyr_0.5.0 purrr_0.2.2 readr_1.1.0 tidyr_0.6.1 tibble_1.3.0
[6] ggplot2_2.2.1 tidyverse_1.1.1 dygraphs_1.1.1.4 shiny_1.0.3 RevoUtilsMath_10.0.0
loaded via a namespace (and not attached):
[1] Rcpp_0.12.10 cellranger_1.1.0 compiler_3.4.0 plyr_1.8.4 forcats_0.2.0 tools_3.4.0 digest_0.6.12
[8] lubridate_1.6.0 jsonlite_1.4 nlme_3.1-131 gtable_0.2.0 lattice_0.20-35 psych_1.7.3.21 DBI_0.6-1
[15] parallel_3.4.0 haven_1.0.0 xml2_1.1.1 httr_1.2.1 stringr_1.2.0 hms_0.3 RevoUtils_10.0.4
[22] htmlwidgets_0.8 grid_3.4.0 R6_2.2.0 readxl_1.0.0 foreign_0.8-67 modelr_0.1.0 reshape2_1.4.2
[29] magrittr_1.5 scales_0.4.1 htmltools_0.3.6 rvest_0.3.2 assertthat_0.2.0 mnormt_1.5-5 colorspace_1.3-2
[36] mime_0.5 xtable_1.8-2 httpuv_1.3.3 stringi_1.1.5 lazyeval_0.2.0 munsell_0.4.3 broom_0.4.2
[43] zoo_1.8-0
【问题讨论】:
-
您没有使用
mutate_at的任何特殊原因?请注意,错误仍然存在 -
@GGamba 不,我当然可以切换到另一种解决方案。但是,我不知道为什么它不起作用,或者即使它应该起作用。