我需要能够提取包含我正在寻找的精确字符串的列。例如,我有这个数据框x:
structure(list(Time = structure(1L, .Label = "1/1/2015", class = "factor"),
WTAD..Linux..Linux.Percent.of.Physical.Memory.and.Swap.Used.on.web02.Total.Phys.Mem.MB. = 3555L,
WTAD..Linux..Linux.Percent.of.Physical.Memory.and.Swap.Used.on.web02.Total.Phys.Mem.Free.MB. = 55L,
WTAD..Linux..Linux.Percent.of.Physical.Memory.and.Swap.Used.on.web02.Total.Swap.Free.MB. = 44L,
WTAD..Linux..Linux.Percent.of.Physical.Memory.and.Swap.Used.on.web02.Total.Cache.Free.MB. = 66L,
WTAD..Linux..Linux.Percent.of.Physical.Memory.and.Swap.Used.on.web02.Total.Swap.And.Cache.Free.MB. = 44L,
WTAD..Linux..Linux.Percent.of.Physical.Memory.and.Swap.Used.on.web02.Total.Percent.Free = 44L,
WTAD..Linux..Linux.Percent.of.Physical.Memory.and.Swap.Used.on.web02.Round.Trip.Time = 44L), .Names = c("Time",
"WTAD..Linux..Linux.Percent.of.Physical.Memory.and.Swap.Used.on.web02.Total.Phys.Mem.MB.",
"WTAD..Linux..Linux.Percent.of.Physical.Memory.and.Swap.Used.on.web02.Total.Phys.Mem.Free.MB.",
"WTAD..Linux..Linux.Percent.of.Physical.Memory.and.Swap.Used.on.web02.Total.Swap.Free.MB.",
"WTAD..Linux..Linux.Percent.of.Physical.Memory.and.Swap.Used.on.web02.Total.Cache.Free.MB.",
"WTAD..Linux..Linux.Percent.of.Physical.Memory.and.Swap.Used.on.web02.Total.Swap.And.Cache.Free.MB.",
"WTAD..Linux..Linux.Percent.of.Physical.Memory.and.Swap.Used.on.web02.Total.Percent.Free",
"WTAD..Linux..Linux.Percent.of.Physical.Memory.and.Swap.Used.on.web02.Round.Trip.Time"
), class = "data.frame", row.names = c(NA, -1L))
我只需要提取包含此完全匹配的列" .Total.Phys.Mem.MB。"
当我这样做时:
x[,grepl(".Total.Phys.Mem.MB.", colnames(x)[2:ncol(x)])]
我没有得到包含此字符串的列" .Total.Phys.Mem.MB。"。有没有更好的方法来提取包含R?
中的字符串的列答案 0 :(得分:1)
library(dplyr)
select(x, contains(".Total.Phys.Mem.MB."))
WTAD..Linux..Linux.Percent.of.Physical.Memory.and.Swap.Used.on.web02.Total.Phys.Mem.MB.
1 3555
答案 1 :(得分:1)
除非定义fixed=TRUE
,否则grepl
会将模式识别为正则表达式;在正则表达式中,点是一个特殊含义的字符,必须进行转义以匹配文字。
> x[grepl("\\.Total\\.Phys\\.Mem\\.MB\\.", colnames(x))]
WTAD..Linux..Linux.Percent.of.Physical.Memory.and.Swap.Used.on.web02.Total.Phys.Mem.MB.
1 3555
OR
> x[grepl('.Total.Phys.Mem.MB.', colnames(x), fixed=TRUE)]
WTAD..Linux..Linux.Percent.of.Physical.Memory.and.Swap.Used.on.web02.Total.Phys.Mem.MB.
1 3555