I am trying to use the subset function within a function I created. However, for some reason it keeps giving an object not found error (even though the same object is found outside of the function). example code:
#import dataframe:
df <- read.csv("/home/df.csv")
#create function with subset in it:
function_w_subset = function(object_type) {
df1 = subset(df, object_type ==0, select = labels)}
#apply function:
df1 = function_w_subset(barrels)
Which gives the error: Error in eval(substitute(expr), data, enclos = parent.frame()) : object 'barrels' not found
Same object outside the function it works fine...
df2 = subset(df, barrels ==0, select = labels) #this works!
I've tried replicating the error with a reproducible example. But for some reason it seems to work fine in the example!?
desks <- c(0, 1, 2, 3)
barrels <- c(3, 2, 1, 0)
labels <- c("A", "A", "B", "B")
df <- data.frame(labels, desks, barrels)
df1 = subset(df, barrels ==0, select = labels)
subset_function = function(object_type) {
df = subset(df, object_type ==0, select = labels)
df
}
df2 = subset_function(barrels)
Any ideas why this error occurs, or an alternative strategy to subset within the function? I've tried the with() function. e.g.
with(df, labels[barrels==0])
Which again works outside the function, but not within...