Hello, i was trying to the my calculation to get Korea, Rep's max population and year that's matching to max populaton.
Therefore i made like that like
apply(gapminder[gapminder$country=="Korea, Rep.",c("pop","year")],2,max)
But i think...it's something wrong....
Can i get an right answer or the solution to make it
Help me
Thanks
I think the point is separation between pop and year.
But i don't know the way...
Hi @Daniel1_1,
Does this give you the information you are looking for:
library(dplyr)
gapminder::gapminder %>%
filter(country == 'Korea, Rep.') %>%
arrange(desc(pop)) %>%
slice(1)
#> # A tibble: 1 x 6
#> country continent year lifeExp pop gdpPercap
#> <fct> <fct> <int> <dbl> <int> <dbl>
#> 1 Korea, Rep. Asia 2007 78.6 49044790 23348.
Created on 2019-12-12 by the reprex package (v0.3.0)
Your code gives the right answer for the wrong reason. apply() will use the chosen function on each column (or row), so you are finding the max of the year column and the max of the pop column. In this case, the highest value for year is 2007, which is the last year in the data set, so it also happens to be the year with the highest population. There is no reason to use apply() for this exercise.
My suggestion is to use which.max(pop), which identifies the row (by number) with the highest value of pop. If you need to use base R, this code would work
library(gapminder)
korea <- gapminder[gapminder$country == "Korea, Rep.", c("year", "pop")]
korea[which.max(korea$pop), ]
#> # A tibble: 1 x 2
#> year pop
#> <int> <int>
#> 1 2007 49044790
Created on 2019-12-13 by the reprex package (v0.3.0)
If you can use the tidyverse, this code would also work
library(dplyr)
library(gapminder)
gapminder %>%
filter(country == "Korea, Rep.") %>%
select(year, pop) %>%
slice(which.max(pop))
#> # A tibble: 1 x 2
#> year pop
#> <int> <int>
#> 1 2007 49044790
Created on 2019-12-13 by the reprex package (v0.3.0)
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.