我有一个与像'dtx1', 'dtx2' (...) 'dtx20'
编号名称变量数据帧。我想选择与“dplyr”的一个子集。我如何可以选择所有的变量?我不希望每一个名字写出来:new_df <- select(old_df, dtx1, dtx2, (...), dtx20)
我已经在这里和谷歌试图多次搜索,但我可能不会有正确的vokabulary。
如果你知道从哪里到哪里要子集可以使用这样的事情:
DF <- dplyr::select(DF, -c(dtxN:dtxM))` #Being N and M the numbers.
如果你不知道哪些是要消除那些,但你他们都有共同的名字的一部分,从@ Mateusz1981借款:
DF <- DF[,- grep("dtx",colnames))]
比方说,我们有一个虚拟的数据帧old_df
:
dtx1 dtx20 dtx d1tx
1 0 0 0 1
2 1 2 0 2
如果您只想让那些在字符串末尾编号列,您可以用dplyr
做到这一点:
library(dplyr)
new_df <- select(old_df, matches("[0-9]+$"))
输出:
dtx1 dtx20
1 0 0
2 1 2
它基本上在列名的结尾匹配任何种类的数量。
如果你想要一个包含特定字符串的所有变量也可以使用contains
:
new_df = old_df %>%
select(contains("dtx"))
dplyr::num_range()
可能是一个不错的选择,可根据您要保留什么dplyr::starts_with()
一起。
df1 <- data.frame(foo=1,dtx1 = 2, dtx2 = 3, bar = 4, dtx3 = 5, dtx4 = 6)
df1
# foo dtx1 dtx2 bar dtx3 dtx4
# 1 1 2 3 4 5 6
library(dplyr)
select(df1, num_range("dtx",1:3))
# dtx1 dtx2 dtx3
# 1 2 3 5
select(df1, starts_with("dtx"))
# dtx1 dtx2 dtx3 dtx4
# 1 2 3 5 6
这是不太安全的:
select(df1, dtx1:dtx4)
# dtx1 dtx2 bar dtx3 dtx4
# 1 2 3 4 5 6