我正在try 导入具有固定列宽的数据.第一个特殊字符出现后,每列的字符数就会发生变化.这可能是什么原因? 文件: 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))

我try 用fread()读取数据.但没有任何论据支持固定列宽度.我的字符串中有空白,所以这不起作用.

推荐答案

下面的代码应该使用基数R的utils::read.fwf()来解决您的问题.如果(未加引号)字符串本身可以包含空白(例如"Jo hn"),则需要此解决方案.否则没有任何争论的data.table::fread()应该可以.

不应使用UTF-8-物料 list 编码(如果可能的话). 参见https://cran.r-project.org/doc/manuals/r-patched/R-data.pdfhttps://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年4月26日,共有reprex v2.1.0

R相关问答推荐

Select R中列未排序的收件箱中的最后一个按顺序编号的列

有没有方法将琴弦完全捕捉到R中的多边形?

将一个载体的值相加,直到达到另一个载体的值

如何在R中正确对齐放射状图中的文本

使用tidyverse / Mutate的存款账户余额

格点中指数、双曲和反双曲模型曲线的正确绘制

使用gcuminc,如何使用逗号格式化风险表?

汇总数据表中两个特定列条目的值

如何从像glm这样的模型中提取系数表的相关性?

为了网络分析目的,将数据框转换为长格式列联表

您是否可以将组添加到堆叠的柱状图

调换行/列并将第一行(原始数据帧的第一列)提升为标题的Tidyr类似功能?

使用R将简单的JSON解析为嵌套框架

Geom_arcbar()中出错:找不到函数";geom_arcbar";

如何提取R中其他字符串和数字之间的字符串?

如何在使用Alpha时让geom_curve在箭头中显示恒定透明度

SHILINY中DT列的条件着色

R中的Desolve:返回的导数数错误

R:使用ApexCharge更改标签在饼图中的位置

从矩阵创建系数图