I have a pattern list
patternlist <- list('one' = paste(c('a','b','c'),collapse="|"), 'two' = paste(1:5,collapse="|"), 'three' = paste(c('k','l','m'),collapse="|"))
that I want to select from to extract rows from a data frame
dataframez <- data.frame('letters' = c('a','b','c'), 'numbers' = 1:3, 'otherletters' = c('k','l','m'))
with this function
pattern.record <- function(x, column="letters", value="one")
{
if (column %in% names(x))
{
result <- x[grep(patternlist$value, x$column, ignore.case=T),]
}
else
{
result <- NA
}
return(result)
}
oddly enough, I get an error when I run it:
> pattern.record(dataframez)
Error in grep(patternlist$value, x$column, ignore.case = T) :
invalid 'pattern' argument
The problem is your use of the
`$`operator.In your function, it is looking a column \ named element called
columnIt is far simpler here to use
`[[`Then
x[[column]]uses whatcolumnis defined as, notcolumnas a name.The relevant lines in
?`$`areYou are trying to use
valueandcolumnas computed indices (i.e. computing whatvalueandcolumnare defined as), thus you need`[[`.The function becomes
note that I’ve also added an argument
pattern_listso it does not depend on an object namedpatternlistexisting somewhere in the parent environments (in your case the global environment.