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
To pick out single or multiple columns use the select() function. The select() function expects a dataframe as it's first input ('argument', in R language), followed by the names of the columns you want to extract with a comma between each name.
across() returns a tibble with one column for each column in . cols and each function in . fns . if_any() and if_all() return a logical vector.
Use the dplyr package to manipulate data frames. Use select() to choose variables from a data frame. Use filter() to choose data based on values. Use group_by() and summarize() to work with subsets of data.
everything() selects all variable. It is also useful in combination with other tidyselect operators. last_col() selects the last variable.
We can use the regex
df %>%
select(matches(paste(Findsensor, collapse="|")))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With