This is my first week working with R and there is one thing about function I cannot seems to manage.
df <- data.frame(a = c(1:10),
b = c("a", "a", "b", "c", "c", "b", "a", "c", "c", "b"))
testF = function(select) {
dum = subset(df, b == select)
}
lapply(unique(df$b), testF)
This function now just prints the the data sets on screen. But I would like to store the results as separate data frames in my workspace. In this example this would give three data frames; a, b and c.
Thank for the help.
A solution using the
list2env
function described in the comment above, assuming you wish to use thesubset
method regardless of potential issues inside a function.If you had a simple example like the one you portray you could access the elements of the list one-by-one as follows and assign each to a variable.
Finally, you could define the function inline such and make use of the (awesome)
data.table
package, thereby avoiding the use of subset:Hope this helps.
Your function needs a return value. See
help("function")
for details.However, for your specific case you can simply use
split
:Roland has the correct solution for the specific problem: more than a
split()
is not needed. Just to make sure:split()
returns a list. To get separate data frames in you workspace, you do:Or, using assign:
A word on subset
This said, some more detail on why your function is plain wrong. First of all, in
?subset
you read:Translates to: Never ever in your life use
subset()
within a function again.A word on returning values from a function
Next to that, a function always returns a result:
return()
statement is used, it returns whatever is given as an argument toreturn()
.In your case, the last line contains an assignment. Now an assignment also returns a value, but you don't see it. It's returned
invisibly
. You can see it by wrapping it in parentheses, for example:This is absolutely unnecessary. It's the reason why your function works when used in
lapply()
(lapply catches invisible output), but won't give you any (visible) output when used at the command line. You can capture it though :The assignment in your function doesn't make sense: either you return
dum
explicitly, or you just drop the assignment alltogetherCorrecting your function
So, given this is just an example and the real problem wouldn't be solved by simply using
split()
your function would be :or simply: