Hello Community,
my question regards making multiple decisions like &
and |
. I imported a rather big dataset from an excel sheet (9211 obs., 482 variables). Now, I only want to keep the rows, which have an "1" in one of the first columns (this indicates an Error in the Data and I want to know, how many there are).
What I did was, in short, something like
Data <- read.csv2("Data.csv", header =FALSE)
Data_fail <- subset(Data, (V3 == 1 | V4 == 1 | V5 == 1 | V6 == 1 | V7 == 1), select=c(V1:V60))
In my actual code I'm not only considering V3 to V7 but V3 to V60, repeating the |-decision until V60, which is a lot to write. Is there any way to make it easier? Like (V3|:V60) == 1
, or V3 == 1 | V4 == 1 | ... | V60 == 1
?
library(tidyverse)
filter(rowwise(iris),any(Petal.Length==1.6,
Petal.Width==1.6))
f <- function(x){x==1.6}
filter(rowwise(iris),any(f(Petal.Length),
f(Petal.Width)))
1 Like
Hello nirgrahamuk,
thank you for your answer. I'm very new to rStudio, so I don't know if I implemented your solution in the right way.
I compiled the code you suggested and set
Data_fail <- f(Data)
But this returns a very large Matrix with the only entries being "NA
" or "FALSE
". But what I need is the same output I got with my longer solution.
In my example replace iris with Data
Replace Petal.Length with V3 etc.
Thanks, I tried it in the way:
f <- function(x)(x==1)
Data_fail <- filter(rowwise(Data), any(f(V3), f(V4)))
This seems to work, but I still have to type every "f(V...)
" for all columns from V3 to V60. What I`m looking for would be something like
any(f(V3:V60))
But this doesn't seem to work with this solution.
library(tidyverse)
library(purrr)
f <- function(x){x==.8}
set.seed(42) # for reproducible random ness in example data
example_df <- as.data.frame(matrix(round(runif(100),1),nrow = 10,ncol=10))
empty_choose_names <- filter(example_df,FALSE) %>% select(V3:V7)
(to_do <- names(empty_choose_names))
(list_of_fs <- map_chr(to_do,
~paste(
"f(",.,")"
)) %>% paste0(collapse = ","))
str_to_exec <- paste0("filter(rowwise(example_df),any(",list_of_fs,"))")
(myresult <- eval(str2lang(str_to_exec)))
1 Like
system
Closed
May 18, 2020, 1:19pm
7
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.