为什么我使用 read_fwf() 的代码不能像书中那样工作?

Eve*_*gle 8 r readr tidyverse

我通过 R Cookbook 第二版学习 R。在4.6读取固定宽度记录中,我输入了书中写的代码。但我的代码不像书上那样工作

Fisher    R.A.      1890 1962
Pearson   Karl      1857 1936
Cox       Gertrude  1900 1978
Yates     Frank     1902 1994
Smith     Kirstine  1878 1939
Run Code Online (Sandbox Code Playgroud)

将此行保存为“fixed-width.fwf”和“fixed-width.txt”

并运行代码

f1 = "fixed-width.fwf"
f2 = "fixed-width.txt"

t1 <- read_fwf(f1, fwf_empty(f1, col_names = c("last", "first", "birth", "death")))

t2 <- read_fwf(f2, fwf_empty(f2, col_names = c("last", "first", "birth", "death")))
Run Code Online (Sandbox Code Playgroud)

t1 和 t2 都打印此错误消息

Error: `file` must be a regular file, not a connection
Run Code Online (Sandbox Code Playgroud)

抱歉我的英语水平很低

小智 1

您的工作目录中有一个名为“fixed-width.txt”的文件吗?

运行下面的代码(几乎与您上面提供的内容非常匹配)为我创建所需的输出:

library("tidyverse")

write_lines(
"Fisher    R.A.      1890 1962
Pearson   Karl      1857 1936
Cox       Gertrude  1900 1978
Yates     Frank     1902 1994
Smith     Kirstine  1878 1939",
file = "./fixed-width.txt")

In_txt_file <- "./fixed-width.txt"

In_Data <- read_fwf(In_txt_file, fwf_empty(In_txt_file, col_names = c("Last_Name", "First_Name", "Birth_Date", "Death_Date")))
Run Code Online (Sandbox Code Playgroud)