如何在R中读取几乎每列都有不同字符数的.txt文件

如何在R中读取几乎每列都有不同字符数的.txt文件,r,readr,R,Readr,我对R很陌生,我需要一些帮助。 我有一个txt文件,里面的数据如下: 14853 C001 1 Apples Apples 14854 BX0 0 Oranges Oranges 14855 F00058 0 Apples and Oranges in the, baske

我对R很陌生,我需要一些帮助。 我有一个txt文件,里面的数据如下:

14853 C001    1 Apples                                                      Apples
14854 BX0     0 Oranges                                                     Oranges
14855 F00058  0 Apples and Oranges in the, basket                           Apples and Oranges in the, [basket]
'14853' 'C001' '1' 'Apples' 'Apples'
'14854' 'BX0' '0' 'Oranges' 'Oranges'
'14855' 'F00058' '0' 'Apples and Oranges in the, basket' 'Apples and Oranges in the, [basket]'
所有列都是无标题的,我尝试将它们组织在数据框中,列如下所示:

14853 C001    1 Apples                                                      Apples
14854 BX0     0 Oranges                                                     Oranges
14855 F00058  0 Apples and Oranges in the, basket                           Apples and Oranges in the, [basket]
'14853' 'C001' '1' 'Apples' 'Apples'
'14854' 'BX0' '0' 'Oranges' 'Oranges'
'14855' 'F00058' '0' 'Apples and Oranges in the, basket' 'Apples and Oranges in the, [basket]'
是否有任何方法可以使用R来执行此操作


我用
read.table()
fread()
scan()
,等等尝试了许多不同的方法。

为了解析输入文件,您需要确定文件的列宽。正如@thelatemail所指出的,您有一个固定宽度的格式,可以使用
base
函数
read.fwf
来解决这个问题

我提供以下解决方案:

library(readr)

txt <- paste(
  "14853 C001    1 Apples                                                      Apples",
  "14854 BX0     0 Oranges                                                     Oranges",
  "14855 F00058  0 Apples and Oranges in the, basket                           Apples and Oranges in the, [basket]",
  sep = "\n"
)

df <- read_fwf(txt, fwf_widths(c(6, 7, 2, 60, 36)))

# # A tibble: 3 x 5
#      X1 X2        X3 X4                                X5                                 
#   <int> <chr>  <int> <chr>                             <chr>                              
# 1 14853 C001       1 Apples                            Apples                             
# 2 14854 BX0        0 Oranges                           Oranges                            
# 3 14855 F00058     0 Apples and Oranges in the, basket Apples and Oranges in the, [basket]
库(readr)

txt请参阅
?read.fwf
-您拥有的是一个固定宽度的文件-另请参阅感谢所有人的回答!不过我有一个小问题。我的txt文件是94127行,我想我不能用粘贴的方式使用它。问题是我正在执行以下操作:
df数据正确地存储在数据帧(df)中。但如果可能的话,我想把这个警告去掉。我还想补充一点,每行的宽度与我在问题样本中显示的不同,因此您可以使用我在上述评论中给出的宽度进行回复。