Reputation: 47
I can't get pipes and brackets []
to work together. I suspect I am not understanding how pipes work.
I am trying to answer the following question, using brackets and pipes:
What is the name of the country, that was the richest in 1952? (data is from package gapminder
)
I have tried:
1. df[df$year == 1970,] %>% df[df$money == max(df$money),]["country"]
2. df %>% filter(year=="1970") %>% df[df$money == max(df$money),]["country"]
3. df %>% filter(year=="1970") %>% filter(money == max(df$money))
Using it without pipes - all lines work seperately. I am not looking for another solution to the problem, but rather to understand pipes and brackets better, and to use these to solve the problem.
For 1. and 2. I get the error saying Error in xj[i] : invalid subscript type 'list'
, whilst for 3 I get an empty dataframe which puzzles me.
Upvotes: 0
Views: 2459
Reputation: 98
There are a few different ways to solve this which are more readable. However if you want to use pipes and brackets to understand how they work, then the following code should do that. You were almost there. You can use the '.' operator which represents the output of the last process before the pipe to carry forward
df[df$year == 1970,] %>%
.[.$money == max(.$money),] %>%
.["country"]
Upvotes: 5
Reputation: 942
I think you are almost there.
Try this:
df %>% filter(year == 1970) %>% filter(money == max(money))
you do not need the df$
part. The last option probably returns and empty df because the highest money in the total data frame was observed in a year other than 1970. Also year is probably numeric, so should be used without quotation marks.
Upvotes: 1