Upgrade to Pro — share decks privately, control downloads, hide ads and more …

前処理R 第2回資料

前処理R 第2回資料

第2回 前処理R オンライン開催の発表資料です。

17903fabbd6615c7c178c3eff89bd03e?s=128

mitti1210

April 23, 2022
Tweet

More Decks by mitti1210

Other Decks in Programming

Transcript

  1. tryCatch @MITTI12101 2 # R (2022/04/23)

  2. MITTI Edx Professional Certificate (Data Sciense) GCI GCI2019 Winter

  3. 病棟の機器を一日どのくらい使用しているか集計したい Excelのデータはあります いいですよ!

  4. ここの平均が欲しい 数十ヶ月ある

  5. この行だけ読み込めばOK? readxl::read_excel(range=”B25:AF25”) でも機器の数って変わってそう・・・

  6. 【作戦】 1, 1行目以外を読み込む 2, 計の行のみにする 3, A列を消して数字だけにする 4, 平均を計算する 完成予想

  7. library(readxl) library(tidyverse) file <- "test.xlsx sheets <- excel_sheets(file) temp <-

    read_excel(file, sheet = 1, skip = 1) temp %>% filter(...1 == " ") %>% select(-1) %>% rowMeans(na.rm = TRUE) [1] 8.677419 1 ReadSheet <- function(file, sheet){ temp <- read_excel(file, sheet = sheet, skip = 1) mean <- temp %>% filter(...1 == " ") %>% select(-1) %>% rowMeans(na.rm = TRUE) year <- str_extract(sheet, "^20[0-9][0-9]") month <- str_extract(sheet,"[0-9]*$") result <- tibble( year = as.integer(year), momth = as.integer(month), value = mean ) return(result) } ReadSheet(file, sheets[1]) [1] 8.677419
  8. map_dfr(sheets,~ReadSheet(file, .x)) 1 1 map

  9. for (sheet in sheets) { tryCatch( { ReadSheet(file, sheet) #

    }, error = function(e){ print(paste0(sheet, )) # } ) } tryCatch
  10. character

  11. ReadSheet <- function(file, sheet){ temp <- read_excel(file, sheet = sheet,

    skip = 1) mean <- temp %>% filter(...1 == " ") %>% select(-1) %>% mutate(across(everything(), as.numeric)) %>% # 1 rowMeans(na.rm = TRUE) year <- stringr::str_extract(sheet, "^20[0-9][0-9]") month <- stringr::str_extract(sheet,"[0-9]*$") result <- tibble( year = as.integer(year), momth = as.integer(month), value = mean ) return(result) } ReadSheet(file, sheets[7])
  12. map_dfr(sheets,~ReadSheet(file, .x)) map

  13. csv map tryCatch

  14. ENJOY!!