如何提取与R中任意字符匹配的列名?
我有一个叫做t的数据框:如何提取与R中任意字符匹配的列名?,r,regex,R,Regex,我有一个叫做t的数据框: dput(t) structure(list(Server = structure(c(2L, 3L, 4L, 5L, 1L, 1L), .Label = c("", "Server1", "Server2", "Server3", "Server4"), class = "factor"), Date = structure(c(2L, 3L, 4L, 5L, 1L, 1L), .Label = c("", "7/17/2017 15:01",
dput(t)
structure(list(Server = structure(c(2L, 3L, 4L, 5L, 1L, 1L), .Label = c("",
"Server1", "Server2", "Server3", "Server4"), class = "factor"),
Date = structure(c(2L, 3L, 4L, 5L, 1L, 1L), .Label = c("",
"7/17/2017 15:01", "7/17/2017 15:02", "7/17/2017 15:03",
"7/17/2017 15:04"), class = "factor"), Host_CPU = c(1.161323547,
6.966178894, 0.656402588, 0.555137634, NA, NA), UsedMemPercent = c(11.33,
11.38, 11.38, 11.38, NA, NA), MY_REPORTING_NYAPP = c(1.05,
0.65, 0.52, 0.32, NA, NA)), .Names = c("Server", "Date",
"Host_CPU", "UsedMemPercent", "MY_REPORTING_NYAPP"), class = "data.frame", row.names = c(NA,
-6L))
我需要能够grep列的名称,这些列可能包括任何由under-score分隔的字符串
比如说,
app<-c("MY_NYAPP")
app如果我理解正确,如果输入是“MY_app”,您想检查哪些列名同时包含“MY”和“app”
希望这能有所帮助。t[grep('''u',names(t))]
?@alistaire,我需要一个所有单词都用“''u'分隔的app1,然后var=app1中的任何值都与列名匹配。grep(粘贴(unlist)(strsplit(''u',names(t),value=TRUE),''u')),collapse=''124',names(t),value=TRUE)
?不过,这似乎毫无意义;你应该用一个期望的结果和足够大的上下文来提问,以便为你指明一个更直接的方法。grep(sub(“'u'”、'u124'、'MY_NYAPP')、names(t))
更短。这将返回名称中包含“MY”或“NYAPP”的列的索引。
app1<-unlist(strsplit(app, "_"))
var<-grep(app1,names(t), value=TRUE)
t = structure(list(Server = structure(c(2L, 3L, 4L, 5L, 1L, 1L), .Label = c("",
"Server1", "Server2", "Server3", "Server4"), class = "factor"),
Date = structure(c(2L, 3L, 4L, 5L, 1L, 1L), .Label = c("",
"7/17/2017 15:01", "7/17/2017 15:02", "7/17/2017 15:03",
"7/17/2017 15:04"), class = "factor"), Host_CPU = c(1.161323547,
6.966178894, 0.656402588, 0.555137634, NA, NA), UsedMemPercent = c(11.33,
11.38, 11.38, 11.38, NA, NA), MY_REPORTING_NYAPP = c(1.05,
0.65, 0.52, 0.32, NA, NA)), .Names = c("Server", "Date",
"Host_CPU", "UsedMemPercent", "MY_REPORTING_NYAPP"), class = "data.frame", row.names = c(NA,
-6L))
app<-c("MY_NYAPP")
app2 = unlist(strsplit(app,"_"))
colnames(t)[rowSums(sapply(app2, function(x) grepl(x,colnames(t))))==length(app2)]
[1] "MY_REPORTING_NYAPP"