【问题标题】:Subset the Orginal dataframe with different combinations of 2 factor variables使用 2 个因子变量的不同组合对原始数据框进行子集
【发布时间】:2023-04-06 02:10:01
【问题描述】:

我有一个包含 11 列和 18350 个观察值的数据集,其中包含可变的公司和区域。有 9 家公司 (company-0) 分布在 5 个区域(region-0 到 region-5),并非所有公司都存在于所有区域。我想为公司和地区的每个组合创建一个单独的数据框。你可以看到这样- 公司0-区域1, company0-region10, 公司0-区域7, 公司1-区域5, company2-region0, 公司3-区域2, 公司4-区域3, 公司5-区域7, 公司6-区域6, 公司8-区域9, company9-region8

因此我在 R 中需要 11 个不同的数据帧。不可能有其他组合 任何其他方法将不胜感激。 提前致谢

我用split函数来得到一个列表-

p<-split(tsog1,list(tsog1$company),drop=TRUE)

现在我有一个数据框列表,我无法将该列表中的每个元素转换为单独的数据框。

我也尝试过使用循环,但无法获得唯一的命名数据框。

v<-c(1:9)
p<-levels(tsog1$company)
for (x in v)
{
  x.tsog1<-subset(tsog1,tsog1$company==p[x])
}

Dataset Image

【问题讨论】:

  • 您能在此处添加可重现的数据以供我们帮助您吗?请在您的问题中添加dput(data) 输出。
  • 嘿!我是堆栈新手,我想添加数据集,但我想知道该怎么做??
  • R 环境中读取数据后,运行dput(head(data)),然后将输出粘贴到此处。

标签: r


【解决方案1】:

您可以为区域公司组合创建一个列,并按该列进行拆分。

例如:

library(tidyverse)

# Create a df with 9 regions, 6 companies, and some dummy observations (3 per case)
df <- expand.grid(region = 0:8, company = 0:5, dummy = 1:3 ) %>% 
  mutate(x = round(rnorm((54*3)),2)) %>% 
  select(-dummy) %>% as_tibble()

# Create the column to split, and split.
df %>% 
  mutate(region_company = paste(region,company, sep = '_')) %>% 
  split(., .$region_company)

现在,获得数据框列表后该怎么做,取决于您接下来的步骤。例如,如果您想保存它们,您可以使用walklapply

为了节省:

df_list <- df %>% 
  mutate(region_company = paste(region,company, sep = '_')) %>% 
  split(., .$region_company)

iwalk(df_list,function(df, nm){
  write_csv(df, paste0(nm,'.csv'))
})

或者,如果您只是想访问它:

> df_list$`0_4`
# A tibble: 3 x 4
  region company     x region_company
   <int>   <int> <dbl> <chr>         
1      0       4  0.54 0_4           
2      0       4  1.61 0_4           
3      0       4  0.16 0_4 

【讨论】:

    猜你喜欢
    • 2019-09-17
    • 2020-10-03
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 2015-12-24
    • 1970-01-01
    • 2018-04-04
    相关资源
    最近更新 更多