问题描述
我有以下数据框,它是 read_excel
的输出,在 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")
如何以灵活的动态方式选择列 ..3
到 Z
(不取决于数量或表格宽度)。我正在考虑以下方面:
t %>% select(-starts_with(".."):-last_col())
但这会发出警告,因为 starts_with
返回两个值。
解决方法
我们可以强制选择第一个:
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())
,
您可以使用基础 R 来实现:
select *
into v_row
from group_matrix gm
where gm.group_code= p_group_code
and ( (p_code is null and gm.code is null)
or gm.code = p_code )
也可以与 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
一起使用:
select()
附注。不要在 R 中使用 t %>%
select(which(cumsum(startsWith(names(t),"..")) == 0))
作为变量名,因为它是一个函数名。