r语言 - dplyr选择一个_of()助手返回警告



我有两个主要的数据框架,我想删除2列列名称:

df1 <- structure(list(a = c(1, 2), b = c(3, 4), c = c(5, 6), d = c(7, 
8), e = c(9, 10)), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame"))
df2 <- structure(list(a = c(1, 2), b = c(3, 4), c = c(5, 6)), row.names = c(NA, 
-2L), class = c("tbl_df", "tbl", "data.frame"))

我想在以下列表中删除任何列名:" c"," d"," e"。

当我只使用one_of()选择助手时,我会得到警告:

> tibble(a = c(1,2), b = c(3,4), c = c(5,6)) %>% select(-one_of("c","d","e"))
# A tibble: 2 x 2
      a     b
  <dbl> <dbl>
1     1     3
2     2     4
Warning message:
Unknown columns: `d`, `e` 

和0警告更大的警告。

请建议如何在没有警告的情况下按列名称过滤?如果我想忽略的列中存在one_of()中的存在,否则请保留它。

我希望我的答案能解决您的问题,我使用 select_if 函数,而不是使用Select的Helper函数。如果您想进一步了解select_if type ?select_if in rstudio console

tibble(a = c(1,2), b = c(3,4), c = c(5,6)) %>% select_if(colnames(.) %in% c("a","c","d","e"))

谢谢!

您可以使用

options(warn=-1)

这将在全球范围内关闭警告消息,以打开它,您可以按照以下方式运行命令。

options(warn=0) 

不建议这样做,只需解决您的要求即可。

仅为此代码提供警告,您可以使用TryCatch():

tryCatch(
suppressWarnings( tibble(a = c(1,2), b = c(3,4), c = c(5,6)) %>%
select(-one_of("c","d","e"))  
  )
  );

相关内容

最新更新