-1

I have a DataFrame with three columns:region, year, grdp.

How do I group data with the same name in 'region' column.

Here's the code to create a sample dataset:

enter image description here

Here's the desired result: store data of values with the same name in the 'region' column

ex) 'region' column has three "서울특별시" data. I want to group the three "서울특별시" data in three columns and assign it to a variable

enter image description here

김준서
  • 1
  • 1
  • 4
    Providing text instead of images helps to get much faster recommendations from the community – RF1991 Apr 15 '22 at 15:28
  • 1
    It's not clear on what you done to the data. Do you want a summary mean of GRDP by region? – Phil Apr 15 '22 at 15:34
  • 1
    See `split(mtcars, mtcars$cyl)`, perhaps in your case you'd use `grdp_spl <- split(grdp, grdp$region)` to split by region into a list of three frames. From there, you can reference `grdp_spl[[1]]` or by name. – r2evans Apr 15 '22 at 15:43

1 Answers1

2

I'm not completely understanding the question, but I think one of these two might solve what you're looking for?

library(dplyr)
df <- data.frame(region=sample(c('x','y','z'),100,replace=TRUE),
                 year=sample(c(2017,2018,2019),100,replace=TRUE),
                 GRDP=sample(200000000:400000000,100))
regions <- unique(df$region)[order(unique(df$region))]

#OPTION 1
for(i in 1:length(regions)){
    assign(tolower(LETTERS[i]),df %>% filter(region==regions[i]))
}
a
b
c

#OPTION 2
ltrs <- tolower(LETTERS[1:length(regions)])
df['ex)'] <- sapply(df$region,FUN=function(x){ltrs[which(regions==x)]})
head(df)
burchz
  • 55
  • 5