Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 删除从第一列匹配正则表达式开始的列范围_R_Dplyr_Tidyselect - Fatal编程技术网

R 删除从第一列匹配正则表达式开始的列范围

R 删除从第一列匹配正则表达式开始的列范围,r,dplyr,tidyselect,R,Dplyr,Tidyselect,我有以下数据框,它是excel中缺少列名的read\u excel的输出: t <- tibble(A=rnorm(3), B=rnorm(3), "x"=rnorm(3), "y"=rnorm(3), Z=rnorm(3)) colnames(t)[3:4] <- c("..3", "..4") 但这给出了一个警告,因为以开头\u返回两个值。您可以使用基本R: t[cumsum(startsWith

我有以下数据框,它是excel中缺少列名的
read\u excel
的输出:

t <- tibble(A=rnorm(3), B=rnorm(3), "x"=rnorm(3), "y"=rnorm(3), Z=rnorm(3))
colnames(t)[3:4] <-  c("..3", "..4")

但这给出了一个警告,因为
开头\u返回两个值。

您可以使用基本R:

t[cumsum(startsWith(names(t), "..")) == 0]

# # A tibble: 3 x 2
#       A       B
#   <dbl>   <dbl>
# 1 -1.56 -0.0747
# 2 -1.68 -0.847 
# 3 -1.23 -1.20

注意:不要将
t
用作R中的变量名,因为它是一个函数名。

我们可以强制选择第一个:

t %>% select(-c(starts_with("..")[ 1 ]:last_col()))
# # A tibble: 3 x 2
#       A      B
#   <dbl>  <dbl>
# 1 0.889  0.505
# 2 0.655 -2.15 
# 3 1.34  -0.290

不是答案-但使用
dplyr::rename_at()
重命名列可能更容易,因为“.j”形式的列名称无效。可能
t%>%select(-start_with(“…”)[1]:-last_col())
?为了澄清一下,您的预期输出是A列和B列,对吗?我们想排除从…开始的所有COL。。列到最后一列?@zx8754是的,谢谢你,笨蛋。您想将其作为答案发布吗?我已将其修改为
select(-first(以“…”)开头):-last\u col())
@c0bra太好了,添加了您的选项,与我的基本方法相比肯定更整洁。
t %>% 
  select(which(cumsum(startsWith(names(t), "..")) == 0))
t %>% select(-c(starts_with("..")[ 1 ]:last_col()))
# # A tibble: 3 x 2
#       A      B
#   <dbl>  <dbl>
# 1 0.889  0.505
# 2 0.655 -2.15 
# 3 1.34  -0.290
select(-first(starts_with("..")):-last_col())