Subsetting a data frame in a function using another data frame as parameter
Posted
by
lecodesportif
on Stack Overflow
See other posts from Stack Overflow
or by lecodesportif
Published on 2011-01-14T17:13:08Z
Indexed on
2011/01/14
18:53 UTC
Read the original article
Hit count: 358
I would like to submit a data frame to a function and use it to subset another data frame.
This is the basic data frame:
foo <- data.frame(var1= c('1', '1', '1', '2', '2', '3'), var2=c('A', 'A', 'B', 'B', 'C', 'C'))
I use the following function to find out the frequencies of var2
for specified values of var1
.
foobar <- function(x, y, z){
a <- subset(x, (x$var1 == y))
b <- subset(a, (a$var2 == z))
n=nrow(b)
return(n)
}
Examples:
foobar(foo, 1, "A") # returns 2
foobar(foo, 1, "B") # returns 1
foobar(foo, 3, "C") # returns 1
This works. But now I want to submit a data frame of values to foobar
. Instead of the above examples, I would like to submit df
to foobar
and get the same results as above (2, 1, 1)
df <- data.frame(var1=c('1','1','3'), var2=c("A", "B", "C"))
When I change foobar
to accept two arguments like foobar(foo, df)
and use y[, c(var1)]
and y[, c(var2)]
instead of the two parameters x
and y
it still doesn't work. Which way is there to do this?
© Stack Overflow or respective owner