R:readr:如何只为一个(有问题的)列(而不是全部)指定数据类型



Readr 是一个很棒的软件包。但是人们懒得为每列指定数据类型。(例如,在 30 个中)。

检查解析失败可能会发现只有一列是关键问题。

见下文

fname='c:/q/net/SnomedCT_RF2Release_INT_20160131/Full/Terminology/sct2_Concept_Full_INT_20160131.txt'
> snm<-read_delim(fname,delim='t')
Warning: 4016 parsing failures.
   row col   expected      actual
528950  id an integer 11000119105
528951  id an integer 11000119105
528952  id an integer 41000119109
528953  id an integer 61000119108
528954  id an integer 81000119104
...... ... .......... ...........
.See problems(...) for more details.
> probs<-problems(snm)
> table(probs$col)
  id 
4016 
> 

如何在数据集中仅指定一列(在我的例子中为列 ID)的数据类型。(要做角色)

names(snm)
[1] "id"                 "effectiveTime"      "active"             "moduleId"           "definitionStatusId"

通过使用 cols 函数在 col_types 参数中指定该列,其余列将保持原样。例如,要将hp列指定为 mtcars 中的字符,请使用"c"表示字符。

library(readr)
write_delim(mtcars, path = "test.txt")
test <- read_delim("test.txt", delim = " ", col_types = cols(hp = "c"))
str(test)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : int  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : chr  "110" "110" "93" "110" ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : int  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : int  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: int  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: int  4 4 1 1 2 1 4 2 2 4 ...
有关详细信息,请参阅

readr列类型晕影 https://cran.r-project.org/web/packages/readr/vignettes/column-types.html

最新更新