gpt4 book ai didi

r - readr 中允许的 "col_*()"形式的列对象是什么?

转载 作者:行者123 更新时间:2023-12-05 01:10:12 26 4
gpt4 key购买 nike

readr::read_csv 误读了我正在加载的文件中的某些列类型,因此我想使用 cols 手动设置它们。

?read_csv 中,它表示 col_types 参数应该是 _"'NULL' 之一、'cols()' 规范或字符串。参见 'vignette("column-types")' 更多细节”。好吧,vignette("column-types") 给出了 vignette("column-types") not found 所以我尝试了 ?cols。它说它接受“由‘col_*()’或其缩写字符名称创建的列对象”。

可接受的函数或缩写字符名称是什么?我在哪里可以找到这些信息? readr 1.1.1 顺便说一句。

最佳答案

col_double, col_integer, col_character, col_date, col_factor, .etc

library(readr)

mtcars <- read_csv(readr_example("mtcars.csv"), col_types =
cols(
mpg = col_double(),
cyl = col_integer(),
disp = col_double(),
hp = col_integer(),
drat = col_double(),
vs = col_integer(),
wt = col_double(),
qsec = col_double(),
am = col_integer(),
gear = col_integer(),
carb = col_integer()
)
)
mtcars

#> # A tibble: 32 x 11
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> <dbl> <int> <dbl> <int> <dbl> <dbl> <dbl> <int> <int> <int> <int>
#> 1 21 6 160 110 3.9 2.62 16.5 0 1 4 4
#> 2 21 6 160 110 3.9 2.88 17.0 0 1 4 4
#> 3 22.8 4 108 93 3.85 2.32 18.6 1 1 4 1
#> 4 21.4 6 258 110 3.08 3.22 19.4 1 0 3 1
#> 5 18.7 8 360 175 3.15 3.44 17.0 0 0 3 2
#> 6 18.1 6 225 105 2.76 3.46 20.2 1 0 3 1
#> 7 14.3 8 360 245 3.21 3.57 15.8 0 0 3 4
#> 8 24.4 4 147. 62 3.69 3.19 20 1 0 4 2
#> 9 22.8 4 141. 95 3.92 3.15 22.9 1 0 4 2
#> 10 19.2 6 168. 123 3.92 3.44 18.3 1 0 4 4
#> # ... with 22 more rows

或者,您可以使用紧凑的字符串表示形式,其中每个字符代表一列:c = 字符i = 整数n = 数字d = doublel = 逻辑, D = 日期, T = 日期时间, t = 时间, ? = guess,或 _/- 跳过该列。

mtcars_select <- read_csv(readr_example("mtcars.csv"), 
col_types = cols_only(mpg = 'd', cyl = 'i', hp = 'i',
qsec = 'd', gear = 'i'),
na = c("NA", "N/A", "-9999", "-999"))
mtcars_select

#> # A tibble: 32 x 5
#> mpg cyl hp qsec gear
#> <dbl> <int> <int> <dbl> <int>
#> 1 21 6 110 16.5 4
#> 2 21 6 110 17.0 4
#> 3 22.8 4 93 18.6 4
#> 4 21.4 6 110 19.4 3
#> 5 18.7 8 175 17.0 3
#> 6 18.1 6 105 20.2 3
#> 7 14.3 8 245 15.8 3
#> 8 24.4 4 62 20 4
#> 9 22.8 4 95 22.9 4
#> 10 19.2 6 123 18.3 4
#> # ... with 22 more rows

甚至更短

mtcars <- read_csv(readr_example("mtcars.csv"), col_types = "di_i__d__i_")
mtcars

# A tibble: 32 x 5
mpg cyl hp qsec gear
<dbl> <int> <int> <dbl> <int>
1 21 6 110 16.5 4
2 21 6 110 17.0 4
3 22.8 4 93 18.6 4
4 21.4 6 110 19.4 3
5 18.7 8 175 17.0 3
6 18.1 6 105 20.2 3
7 14.3 8 245 15.8 3
8 24.4 4 62 20 4
9 22.8 4 95 22.9 4
10 19.2 6 123 18.3 4
# ... with 22 more rows

引用:

https://cran.r-project.org/web/packages/readr/vignettes/readr.html
https://www.rdocumentation.org/packages/readr/versions/1.1.1/topics/cols

关于r - readr 中允许的 "col_*()"形式的列对象是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50651898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com