Dplyr select_和starts_with对变量列表中的多个值 [英] Dplyr select_ and starts_with on multiple values in a variable list

查看:267
本文介绍了Dplyr select_和starts_with对变量列表中的多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从不同位置的不同传感器收集数据,数据输出类似于:

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

(我认为)问题类似于:使用select_和starts_with R

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

我想例如按位置搜索传感器,所以我有一个列表可以搜索数据框,还包括时间戳.但是,当我搜索多个传感器(或传感器类型等)时,搜索就会分崩离析.有没有一种方法可以使用dplyr(NSE或SE)实现这一目标?

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

这是较大管道的一部分(因此使用dplyr),希望将选择与Shiny集成在一起,因此灵活性非常重要.搜索可以是不同的位置或传感器,也可以是基于字符搜索的其他变量.

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.

非常感谢! 续在这里: Dplyr对变量列表第2部分中的多个值进行select_和starts_with

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

推荐答案

我们可以使用正则表达式

We can use the regex

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

这篇关于Dplyr select_和starts_with对变量列表中的多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆