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

3b6akqbq  于 2023-04-18  发布在  其他
关注(0)|答案(1)|浏览(88)

我在R Cookbook第2版学习R。在4.6阅读Fixed-Width Records中,我输入了书中写的代码。但我的代码不像书中那样工作

Fisher    R.A.      1890 1962
Pearson   Karl      1857 1936
Cox       Gertrude  1900 1978
Yates     Frank     1902 1994
Smith     Kirstine  1878 1939

将此行保存为“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")))

t1和t2都打印此错误消息

Error: `file` must be a regular file, not a connection

抱歉我的英语水平不高

cwtwac6a

cwtwac6a1#

你有一个文件名为'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")))

相关问题