1

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...

coccolith
  • 47
  • 8
  • [pachamaltese](https://stackoverflow.com/users/3720258) posted an [Answer](https://stackoverflow.com/a/67067035) saying "Please see the excellent answer for [Why is `[` better than `subset`?](https://stackoverflow.com/questions/9860090/why-is-better-than-subset), which points to a fully detailed book chapter ([http://adv-r.had.co.nz/Computing-on-the-language.html](http://adv-r.had.co.nz/Computing-on-the-language.html))" – Scratte Apr 19 '21 at 08:51

1 Answers1

-1

You need to be aware of scoping. Inside of your function it is like a separate room, and the inside of the function does not know what is outside. For example, you are using a variable with the name "df" inside your function. But if you look just inside your function, it is completely unclear where this variable would come from. The same goes for "barrels". I repeat, think about the scope of your functions and the rest of the code.

vanao veneri
  • 970
  • 2
  • 12
  • 31