data.frame选择带条件的列

data.frame选择带条件的列,r,R,我有两个问题,但它们非常相似: 1) 我有一个数据帧:test 如果在NAT之后有多个数字,可以使用量词+,或者,如果要选择特定数量的数字或特定范围的数字,可以使用{}进行量化: test[, grepl("^NAT\\d+$", names(test))] # matches one or more numbers test[, grepl("^NAT\\d{2}$", names(test))] # matches exactly 2 numbers test[, grepl("^NAT\\

我有两个问题,但它们非常相似:

1) 我有一个数据帧:
test
如果在
NAT
之后有多个数字,可以使用量词
+
,或者,如果要选择特定数量的数字或特定范围的数字,可以使用
{}
进行量化:

test[, grepl("^NAT\\d+$", names(test))] # matches one or more numbers
test[, grepl("^NAT\\d{2}$", names(test))] # matches exactly 2 numbers
test[, grepl("^NAT\\d{2,4}$", names(test))] # matches the range of 2 to 4 numbers
test[, grepl("^NAT\\d{2,}$", names(test))] # matches the range of 2 to any number of numbers
或者,您可以从软件包
stringr
中使用
stru detect

test[, str_detect(colnames(test), "^NAT\\d$")]
  NAT1 NAT2 NAT3
1    1    2    3
如果在
NAT
之后有多个数字,可以使用量词
+
,或者,如果要选择特定数量的数字或特定范围的数字,可以使用
{}
进行量化:

test[, grepl("^NAT\\d+$", names(test))] # matches one or more numbers
test[, grepl("^NAT\\d{2}$", names(test))] # matches exactly 2 numbers
test[, grepl("^NAT\\d{2,4}$", names(test))] # matches the range of 2 to 4 numbers
test[, grepl("^NAT\\d{2,}$", names(test))] # matches the range of 2 to any number of numbers
或者,您可以从软件包
stringr
中使用
stru detect

test[, str_detect(colnames(test), "^NAT\\d$")]
  NAT1 NAT2 NAT3
1    1    2    3

使用
dplyr
,我们可以使用
匹配项

library(dplyr)
test %>%
   select(matches("^NAT.*\\d+$"))

使用
dplyr
,我们可以使用
匹配项

library(dplyr)
test %>%
   select(matches("^NAT.*\\d+$"))

第一个任务和第二个任务有什么区别?@camille最后两个列名以S1和S2结尾:字母和数字第一个任务和第二个任务有什么区别?@camille最后两个列名以S1和S2结尾:字母和数字谢谢,如果在NAT后面有两个数字的列名,该函数如何工作?就像我编辑了
NAT11 NAT12
一样,我已经编辑了答案,包括了你新问题的答案。谢谢!那很好用。我想知道这些表达的意思是什么:
“^xxxx\\d+$”
不知道你为什么问这个。但是,
“^xxxx\\d+$”
匹配4次
x
(第一个必须出现在字符串的开头),然后是一个或多个数字(最后一个必须出现在字符串的末尾),例如,
xxxxxxxx2
xxxxxx123456789
。我再次编辑了答案,以包含更多选项。谢谢,如果在NAT后面有两个数字的列名,该函数如何工作?就像我编辑了
NAT11 NAT12
一样,我已经编辑了答案,包括了你新问题的答案。谢谢!那很好用。我想知道这些表达的意思是什么:
“^xxxx\\d+$”
不知道你为什么问这个。但是,
“^xxxx\\d+$”
匹配4次
x
(第一次必须出现在字符串的开头),然后是一个或多个数字(最后一个必须出现在字符串的末尾),例如,
xxxxxxxx2
xxxxxx123456789
。我再次编辑了答案,以包含更多选项。