user1471980
user1471980

Reputation: 10626

how do you extract data from data frame columns that contain certain text

I have this data frame:

dput(df)

structure(list(Time = structure(1:4, .Label = c("1/29/2015 2:00", 
"1/29/2015 2:10", "1/29/2015 2:20", "1/29/2015 2:30"), class = "factor"), 
    WTAD..SNMP..AppTier.BIGIP.SNMP.CPU.5min.avg.on.Web01.Content.Match = structure(c(1L, 
    1L, 1L, 1L), .Label = "n/a", class = "factor"), WTAD..SNMP..AppTier.BIGIP.SNMP.CPU.5min.avg.on.Web01.Status = structure(c(1L, 
    1L, 1L, 1L), .Label = "n/a", class = "factor"), WTAD..SNMP..AppTier.BIGIP.SNMP.CPU.5min.avg.on.Web01.Value = c(12L, 
    12L, 12L, 12L), WTAD..SNMP..AppTier.BIGIP.SNMP.Memory.on.Web01.Content.Match = structure(c(1L, 
    1L, 1L, 1L), .Label = "n/a", class = "factor")), .Names = c("Time", 
"WTAD..SNMP..AppTier.BIGIP.SNMP.CPU.5min.avg.on.Web01.Content.Match", 
"WTAD..SNMP..AppTier.BIGIP.SNMP.CPU.5min.avg.on.Web01.Status", 
"WTAD..SNMP..AppTier.BIGIP.SNMP.CPU.5min.avg.on.Web01.Value", 
"WTAD..SNMP..AppTier.BIGIP.SNMP.Memory.on.Web01.Content.Match"
), class = "data.frame", row.names = c(NA, -4L))

I am trying to column that contains this: CPU.5min.avg.on.*.Value"

library(dplyr)
df<-select(df, Time, contains("CPU.5min.avg.on.*.Value"))

This work on windows R but not linux. Any ideas what I'm doing wrong?

Upvotes: 2

Views: 70

Answers (2)

Colonel Beauvel
Colonel Beauvel

Reputation: 31171

Base R solution:

df[,c("Time",colnames(df)[sapply(colnames(df), function(u) grepl("CPU.5min.avg.on.*.Value",u))])]

Upvotes: 2

Marat Talipov
Marat Talipov

Reputation: 13304

dplyr solution:

select(df, Time, matches('CPU.5min.avg.on.*.Value'))

Actually, I am puzzled that your solution worked under Windows. ?select documentation says:

contains(x, ignore.case = TRUE): selects all variables whose name contains x

matches(x, ignore.case = TRUE): selects all variables whose name matches the regular expression x

and you're trying to match the regular expression in your code, so it shouldn't work with contain under any OS.

Upvotes: 2

Related Questions