Reputation: 21
I need to select different rows from a data frame and put them into their individual data frame.
My data frame has 7 variables: a country variable and 6 macro-level variables such as gdp, economic growth, depth etc..
I have 9 different countries in my data frame which means I have 9 rows and 7 columns.
Now I need to "select" 9 individual rows (one row for each country) in oder to have 9 different sub data frames that each consist just of one country and the values of its 6 macro-variables.
I tried the following command but it did not work:
df.country1 <- df %>%
select(variable1, variable2, variable3, variable4, variable5, variable6) %>%
filter(country=="country1")
Could someone please help me with the correct command for my problem? Thanks!
Upvotes: 0
Views: 81
Reputation: 887851
We can split
by 'country' and then select
those 'variable' to get a list
of data.frame
library(dplyr)
lst <- df %>%
split(.$country) %>%
select_at(vars(starts_with("variable")))
But, if this is to do some calculations based on each 'country', instead of doing the split
, use group_by(country)
It is better not to have individual objects in the global environment and all the operations can be done within the list
object itself. However, if the objects are really required, then use list2env
names(lst) <- paste0("df.", names(lst))
list2env(lst, envir = .GlobalEnv)
In the OP's code, it is not working, because after the select
step, there are only 'variable' columns and no 'country' column to filter
(assuming that it is not a grouped dataset). The filter
step should be before the select
Upvotes: 2