Dplyr select_ and starts_with on several values ​​in the variable list, part 2

This is a continuation from my question earlier: Dplyr select_ and starts_with for several values ​​in the variable list

I collect data from different sensors in different places, 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),"Sensor1a Pressure"=c(1001, 1000, 1002, 1004, 1000), "Sensor2 Temp"=c(15,18,15,14,19),"Sensor2 Pressure"=c(1001, 1000, 1002, 1004, 1000), "Sensor2 DewPoint"=c(10,11,10,9,12),"Sensor2 Humidity"=c(90, 100, 90, 100, 80))

The problem (I think) is similar to: Using select_ and starts_with R or select columns based on multiple rows with dplyr

I want to search for sensors, for example, by location, so I have a list to search by file frame, as well as a timestamp. But the search falls apart when I search for more than one sensor (or type of sensor, etc.). Is there a way to use dplyr (NSE or SE) to achieve this?

FindLocation = c("date", "Sensor1", "Sensor2")
df %>% select(matches(paste(FindLocation, collapse="|"))) # works but picks up "Sensor1a" and "DewPoint" and "Humidity" data from Sensor2 

I also want to add mixed queries, for example:

 FindLocation = c("Sensor1", "Sensor2") # without selecting "Sensor1a"
 FindSensor = c("Temp", "Pressure") # without selecting "DewPoint" or "Humidity"

, FindSensor FindLocation Temp Pressure Sensor1 Sensor2 ( Sensor1a). :

Sensor1, 1 , 2, 2

!

0
3

purrr . cross2 FindLocation FindSensor. . map_chr, paste, (.). one_of .

library(purrr)

FindLocation = c("Sensor1", "Sensor2")
FindSensor = c("Temp", "Pressure")

columns = cross2(FindLocation, FindSensor) %>%
  map_chr(paste, collapse = ".")

df %>% select(one_of(columns))
+2

df %>% 
  select(matches(paste(c("date", outer(FindLocation, 
                FindSensor, paste, sep=".")), collapse="|")))
+2

- :

library(tidyverse)
wich_col <- df %>% names %>% strsplit("[.]") %>% map_lgl(function(x)x[1]%in%FindLocation&x[2]%in%FindSensor)
df[wich_col]

?

+1

Source: https://habr.com/ru/post/1682431/


All Articles