2017-07-28 71 views
0

这是我的问题早延续:Dplyr select_ and starts_with on multiple values in a variable listDplyr SELECT_和STARTS_WITH多个值的变量列表部分2

我收集来自不同地点不同的充传感器的数据,数据输出是一样的东西:

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

的问题是(我认为)类似:Using select_ and starts_with Rselect columns based on multiple strings with dplyr

我想搜索的LO传感器例如阳离子,所以我有一个列表来搜索数据框,还包括时间戳。但是,当我搜索多个传感器(或传感器类型等)时,搜索会崩溃。有没有使用dplyr(NSE或SE)来实现这一目标的方法?

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

另外我想补充混合搜索,例如:

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

我希望选择联合FindSensor与FindLocation和选择的传感器1和传感器2温度和压力数据(而没有选择Sensor1a)。再次

日期,传感器1温度,传感器1压力传感器2温度,传感器2压力

非常感谢:返回数据帧的数据和列标题!

+0

尝试'DF%>%选择(匹配(膏(C( “日期”,外(FindLocation,FindSensor,糊剂,九月= “”)),崩溃=“|”)))' – akrun

+0

是的,这工作,谢谢! –

回答

2

purrr的一些功能将会很有用。首先,您使用cross2来计算FindLocationFindSensor的笛卡尔乘积。你会得到一个对的列表。然后,您使用map_chrpaste应用于它们,并用点(.)连接位置和传感器字符串。然后你使用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)) 
+0

谢谢,并没有见过cross2之前 - 非常有用的功能! –

1

什么是这样的:

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

+0

作品和感谢! –

2

我们可以使用

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

作品!谢谢并选择日期 –