我正在尝试导入具有固定列宽的数据。第一个特殊字符出现后,每列的字符数发生变化。这可能是什么原因? 文件: https://gist.github.com/1902r/0b596431e15bde833e9d9a0640e12ba7
library(readr)
columns_widths <- c(3, 8, 7)
source_data <- "data.rpt"
source_data_raw <- read_fwf(source_data, fwf_widths(columns_widths))
我尝试使用 fread() 读取数据。但没有任何论据支持固定列宽。我的字符串中有空格,所以这不起作用。
以下代码应该使用基本 R 中的
utils::read.fwf()
来解决您的问题。如果(未加引号的)字符串本身可以包含空格(例如“Jo hn”),您需要此解决方法。否则 data.table::fread()
不带任何参数应该没问题。
不应使用 UTF-8-BOM 编码(如果可能)。 请参阅 https://cran.r-project.org/doc/manuals/r-patched/R-data.pdf 和 https://en.wikipedia.org/wiki/Byte_order_mark
在
readr::read_fwf()
中,固定宽度文件中的列位置指的是字节,而不是字符(请参阅https://github.com/tidyverse/readr/issues/852)。因此,包含多字节字符的行被替换。
library(readr)
columns_widths <- c(3, 8, 7)
source_data <- "https://gist.githubusercontent.com/1902r/0b596431e15bde833e9d9a0640e12ba7/raw/215e50d1db79b4a7aeb3560680a55bba8c9f1503/data.rpt"
source_data_raw <- read_fwf(source_data, fwf_widths(columns_widths))
#> Rows: 4 Columns: 3
#> ── Column specification ────────────────────────────────────────────────────────
#>
#> chr (3): X1, X2, X3
#>
#> ℹ Use `spec()` to retrieve the full column specification for this data.
#> ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
source_data_raw
#> # A tibble: 4 × 3
#> X1 X2 X3
#> <chr> <chr> <chr>
#> 1 ID Name Amount
#> 2 1 Jo hn 100
#> 3 2 Bílušk a 450
#> 4 3 Jane 200
## first read colnames from file
datar_names <- read.fwf(source_data,
widths = columns_widths,
n = 1, fileEncoding = "UTF-8-BOM",
strip.white = TRUE
)
## read data using names from above
datar <- read.fwf(source_data,
widths = columns_widths,
skip = 1, col.names = datar_names,
fileEncoding = "UTF-8-BOM",
strip.white = TRUE
)
datar
#> ID Name Amount
#> 1 1 Jo hn 100
#> 2 2 Bíluška 450
#> 3 3 Jane 200
str(datar)
#> 'data.frame': 3 obs. of 3 variables:
#> $ ID : int 1 2 3
#> $ Name : chr "Jo hn" "Bíluška" "Jane"
#> $ Amount: int 100 450 200
创建于 2024-04-26,使用 reprex v2.1.0