1

首先,请参阅此 url ,了解我正在格式化的数据类型的一个小示例。您会注意到我在工作表中突出显示了我要选择的两个区域。随着项目进出数据集,选择范围需要是动态的。对于第一部分,我认为这段代码就足够了:

library(tidyverse)
library(readxl)

filename <- "MyDataset.xlsx"

#obtain first section of my excel spreadsheet
project_codes <- read_excel(
  path = filename,
  sheet = "Jan18",
  range = "A10:B1000",
  col_names = c("proj_num", "name")
) %>% 
  drop_na() %>% 
  filter(grepl("-", project_codes$proj_num))

第二部分是我被绊倒的地方......我想确保我在电子表格的另一个突出显示区域中选择了与我的“project_codes”完全相同的行子集。

我有许多以完全相同的方式格式化的工作表(并且命名约定是一致的 - Jan18、Feb18、Mar18),所以如果有人可以在解决第 1 部分后帮助我遍历工作表,则可以加分。

4

1 回答 1

2
library(tidyverse)
library(readxl)

filename <- "MyDataset.xlsx"

excel_sheets(filename) %>% 
  set_names() %>% 
  map_df(~ read_excel(
  path = filename,
  sheet = .,
  range = "A6:N1000"
) %>% 
  filter(str_detect(`#`, "-")) %>% 
  select(`#`, `PROJECT NAME`, `Status`, `Cumulative Billings`, `Billing Adjustment`, `Contract Value`), .id = "Month")

# A tibble: 8 x 7
  Month `#`       `PROJECT NAME` Status `Cumulative Billings` `Billing Adjustment` `Contract Value`
  <chr> <chr>     <chr>           <dbl>                 <dbl>                <dbl>            <dbl>
1 Jan18 1-11-0010 Project 1         715                  6723                 2138             1977
2 Jan18 1-11-0011 Project 2        1717                  8330                 8283             2588
3 Jan18 1-11-0012 Project 3        3332                  2908                 4938             7734
4 Jan18 1-11-0013 Project 4        2589                  8714                 6034             1476
5 Jan18 1-11-0014 Project 5         588                  4969                 2161             3334
6 Jan18 1-11-0015 Project 6         820                  7688                 4243             4293
7 Jan18 1-11-0020 Project 20       7287                   333                 9100             3078
8 Jan18 1-11-0030 Project 30       1564                   487                 7249             5508

map_df() will iterate through each sheet (whose names are extracted using excel_sheets()) and create one data frame with a column indicating which sheet the data comes from.

I had to rely on this answer to apply the name of the sheet as its own column.

于 2018-02-17T17:59:39.177 回答