Dplyr select_ and starts_with on multiple values in a variable list

假装没事ソ 提交于 2019-12-22 03:51:42

问题


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="|")))


来源:https://stackoverflow.com/questions/45357806/dplyr-select-and-starts-with-on-multiple-values-in-a-variable-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!