'How can I write this to include multiple conditions?
I am trying to write out excel files as workbooks where columns satisfy more than one condition. I receive errors here with grep function and unexpected }
If I remove the grep function the code executes with the first condition.
Just an example, if first condition == 10, good and If second condition = "test", good folder. Else, bad folder.
This code is embedded in a for loop. 'data' is the frame created in each pass, 'files1' is the name of each excel workbook captured and then written out to desired folder in each pass.
if (nchar(data$`Serial Number:`) == 10) %>%
if grep(pattern = "test",x = data$`Product:`, value = TRUE){
write_xlsx(data, path = (paste0("good/", files1, "x")))
}else{
write_xlsx(data, path = (paste0("bad/", files1, "x")))
}
Solution 1:[1]
I was able to resolve. Code Result:
- Import files from folder and preserve names
- Loop conditions to check for col1 and col5 - Do they have the data I want? If not move to desired path, if yes move to desired path and save while preserving the file name
Please, if anyone has suggestions on how to clean this up, please let know. I'd be curious to know how this could be improved on with piping. Thank you!
files <-
list.files(path = "mypath/", pattern = "*xls")
for (i in 1:length(files)) {
files1 <-
basename(files[i])
files1 <- gsub(pattern = "'", replacement = "" , x = files1)
files1 <- gsub(pattern = "\\*", replacement = "" , x = files1)
data <-
read_excel(paste0("mypath/", files[i]))
data$col1 <- as.character(data$col1)
data <- data %>%
mutate(charCount = nchar(data$col1))
data <- data %>% mutate(across(where(is.character), str_trim))
if(any(grepl(pattern = "input pattern", x = data$charCount)) == FALSE) {
write_xlsx(data, path = (paste0("path1/", files1, "x")))
}
if (any(grepl(pattern = "input pattern", x = data$col1) == TRUE) && any(grepl(pattern = "input pattern",x = data$col5,ignore.case = T) == TRUE)){
write_xlsx(data[,1:11], path = (paste0("path2/", files1, "x")))
}else{
write_xlsx(data[,1:11], path = (paste0("bad/", files1, "x")))
}}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |