STAT545-UBC / Discussion

Public discussion
38 stars 20 forks source link

do is dropping countries #274

Closed molliejmcdowell closed 8 years ago

molliejmcdowell commented 8 years ago

I have a function:

thefit <- function(dat, offset=1952){ stopifnot(is.data.frame(dat)) gapminderaugment <- augment(lm(lifeExp ~ I(year - offset), dat)) gapminderaugment }

and a list of countries: selectedcountries <- c("Japan", "China", "Israel", "Afghanistan", "Cambodia", "Yemen, Rep.", "Canada", "Costa Rica", "Puerto Rico", "Haiti", "Bolivia", "Honduras", "Reunion", "Libya", "Tunisia", "Rwanda", "Gambia", "Angola", "Iceland", "Switzerland", "Spain", "Turkey", "Bosnia and Herzegovina", "Albania")

and I am trying to do() my function to this list: selectedcountriesdf <- newgapminderdf %>% group_by(country) %>% filter(country == selectedcountries) %>% do(thefit(.))

But I get the error: Error: incorrect length (24), expecting: 12

If I leave out group_by(country), I have returned a dataframe without the "country" column that is only 12 rows long, not 24 as I would expect (since I am giving it 24 countries).

How do I apply this function to all 24 countries ?

ksamuk commented 8 years ago

That particular error is caused by using filter(country == selectedcountries), where you probably actually want filter(country %in% selectedcountries).

I also stylistically, you'd probably want to have the filter before the group_by, but it might not matter here.

molliejmcdowell commented 8 years ago

it worked! thanks, kieran!