I am in need of a function that extracts any type of bracket ie (), [], {} and the information in between. I created it and get it to do what I want but I get an annoying warning that I don't really know what it means. I want the annoying warning to go away either by fixing what's wrong with my code or suppressing the warning. I attempted this with suppressWarnings() but it didn't work because I don't think I used it correctly.
This function uses regmatches and requires R version 2.14 or higher
Here's the function below and an example to reproduce the warning. Thank you for the help.
################
# THE FUNCTION #
################
bracketXtract <- function(text, bracket = "all", include.bracket = TRUE) {
bracketExtract <- if (include.bracket == FALSE) {
function(Text, bracket) {
switch(bracket,
square = lapply(Text, function(j) gsub("[\[\]]", "",
regmatches(j, gregexpr("\[.*?\]", j))[[1]],
perl = TRUE)),
round = lapply(Text, function(j) gsub("[\(\)]", "",
regmatches(j, gregexpr("\(.*?\)", j))[[1]])),
curly = lapply(Text, function(j) gsub("[\{\}]", "",
regmatches(j, gregexpr("\{.*?\}", j))[[1]])),
all = { P1 <- lapply(Text, function(j) gsub("[\[\]]", "",
regmatches(j, gregexpr("\[.*?\]", j))[[1]],
perl = TRUE))
P2 <- lapply(Text, function(j) gsub("[\(\)]", "",
regmatches(j, gregexpr("\(.*?\)", j))[[1]]))
P3 <- lapply(Text, function(j) gsub("[\{\}]", "",
regmatches(j, gregexpr("\{.*?\}", j))[[1]]))
apply(cbind(P1, P2, P3), 1, function(x) rbind(as.vector(unlist(x))))
})
}
} else {
function(Text, bracket) {
switch(bracket,
square = lapply(Text, function(j) regmatches(j,
gregexpr("\[.*?\]", j))[[1]]),
round = lapply(Text, function(j) regmatches(j,
gregexpr("\(.*?\)", j))[[1]]),
curly = lapply(Text, function(j) regmatches(j,
gregexpr("\{.*?\}", j))[[1]]),
all = { P1 <- lapply(Text, function(j) regmatches(j,
gregexpr("\[.*?\]", j))[[1]])
P2 <- lapply(Text, function(j) regmatches(j,
gregexpr("\(.*?\)", j))[[1]])
P3 <- lapply(Text, function(j) regmatches(j,
gregexpr("\{.*?\}", j))[[1]])
apply(cbind(P1, P2, P3), 1, function(x) rbind(as.vector(unlist(x))))
})
}
}
if (length(text) == 1) {
unlist(lapply(text, function(x) bracketExtract(Text = text,
bracket = bracket)))
} else {
sapply(text, function(x) bracketExtract(Text = text,
bracket = bracket))
}
}
##################
# TESTING IT OUT #
##################
j <- "What kind of cheese isn't your cheese? {wonder} Nacho cheese! [groan] (Laugh)"
bracketXtract(j, 'round')
bracketXtract(j, 'round', include.bracket = FALSE)
examp2<-data.frame(var1=1:4)
examp2$text<-as.character(c("I love chicken [unintelligible]!", "Me too! (laughter) It's so good.[interupting]",
"Yep it's awesome {reading}.", "Agreed."))
#=================================#
# HERE"S WHERE THE WARNINGS COME: #
#=================================#
examp2$text2<-bracketXtract(examp2$text, 'round')
examp2
examp2$text2<-bracketXtract(examp2$text, 'all')
examp2
See Question&Answers more detail:
os