【问题标题】:How to access a list of tibble to check whether "UTF-8" and run import R如何访问 tibble 列表以检查是否为“UTF-8”并运行 import R
【发布时间】:2019-08-16 10:23:50
【问题描述】:

目标: 在导入和rbind之前检查文件列表是否具有相同的编码,如果不同则停止运行

# files list & check encoding
FL_PATH <- list.files(path,pattern = "*.csv",full.name = T)
library(readr)
lapply(FL_PATH,guess_encoding)

# if there is "UTF-8" , STOP RUN , if "Shift_JIS" , RUN the next scripts below :

# import
library(rio)
DT <- rbindlist(lapply(FL_PATH ,import,sep=",",setclass = "data.table"))

# OVER 500 rows to run if the files are same encoding to rbind
DT[,"NEW_COL":="A"]
DT[,"NEW_COL_2":="B"]
.....

# result of --lapply(FL_PATH,guess_encoding)
> lapply(FL_PATH,guess_encoding)
[[1]]
# A tibble: 3 x 2
  encoding  confidence
  <chr>          <dbl>
1 Shift_JIS       0.8 
2 GB18030         0.76
3 Big5            0.46

[[2]]
# A tibble: 3 x 2
  encoding  confidence
  <chr>          <dbl>
1 GB18030         0.82
2 UTF-8       0.8 
3 Big5            0.44
  • 问题1:如何访问lapply readr的结果变量 检测 UTF-8 和 STOP(如果 UTF-8 存在吗?)
  • 问题2:如何连接大量的正常处理脚本 用“if & STOP run”?

【问题讨论】:

  • 不遍历所有结果,让lapply 只返回最上面的结果怎么样?试试sapply(FL_PATH,function(x) guess_encoding(x)$encoding[1])
  • 谢谢你 Rohit,这正是 ACCESS tibble 的方式,并且读者将第一个提高为最高百分比。但是可以说 grepl("UTF-8",sapply(FL_PATH,function(x)guess_encoding(x)$encoding[1])) 返回 TRUE 和 FALSE ,我不知道如何连接到导入/不导入方法。

标签: r utf-8 import tibble readr


【解决方案1】:

首先,获取最可能的编码:

enc <- sapply(FL_PATH,function(x) guess_encoding(x)$encoding[1])

然后,如果任何文件是 UTF-8,则停止执行。

if(any(grepl('UTF-8',enc)))
  stop('UTF-8 present') # This will stop with an error if true
# Now, read files and rbind
dlist <- lapply(FL_PATH,read_csv)
DT <- rbindlist(dlist)

【讨论】:

  • 天哪,在整个脚本中应用 if 和 STOP 和检查功能的最佳方法
猜你喜欢
  • 2018-05-08
  • 2010-09-12
  • 2017-11-22
  • 1970-01-01
  • 2010-12-01
  • 1970-01-01
  • 2019-05-17
  • 2021-05-30
  • 2012-02-12
相关资源
最近更新 更多