Dplyr select_ and starts_with on multiple values i

2020-08-16 08:00发布

问题:

I am collecting data from differnt sensors in various locations, data output is something like:

df<-data.frame(date=c(2011,2012,2013,2014,2015),"Sensor1 Temp"=c(15,18,15,14,19),"Sensor1 Pressure"=c(1001, 1000, 1002, 1004, 1000),"Sensor1a Temp"=c(15,18,15,14,19),"Sensor2 Temp"=c(15,18,15,14,19),"Sensor2 Pressure"=c(1001, 1000, 1002, 1004, 1000))

The problem is (I think) similar to: Using select_ and starts_with R

I want to search for sensors for example by location so I have a list to search through the dataframe and also include the timestamp. But searching falls apart when I search for more than one sensor (or type of sensor etc). Is there a way of using dplyr (NSE or SE) to achieve this?

Findsensor = c("Sensor1") # one value
test <- df %>% select_(.dots = ~starts_with(Findsensor)) # works

Findsensor = c("date", "Sensor1", "Sensor2") # more values
test <- df %>% select_(.dots = ~starts_with(Findsensor)) # doesn't work

This is part of a larger pipe (hence using dplyr) and wish to integrate the selecting with Shiny so flexibility is important. The searching could be different locations or sensors or some other variable based on character searching.

Many thanks in advance! Continued here: Dplyr select_ and starts_with on multiple values in a variable list part 2

回答1:

We can use the regex

df %>% 
   select(matches(paste(Findsensor, collapse="|")))