read_data_with_switch_R

2022-04-19

当不确定import的数据文件的类型时,如何自动根据文件的扩展名,调用自动的import data函数呢?使用switch函数。

switch的使用

I write the user defined function for read data with different file extensions.

read_data <- function(file) {
  library("tools")
  ext <-  file_ext(file)
  switch(
    ext,
    txt = read.delim(
      file = file,
      header = TRUE,
      sep = "\t",
      stringsAsFactors = FALSE
    ),
    csv = read.csv(
      file = file,
      header = TRUE,
      sep = ",",
      stringsAsFactors = FALSE
    )
  )
  
}

Acknowledgement