0

我获得了一个 .txt 格式的数据集,我需要将其导入 R 进行研究分析。.txt 文件有一列带有数字字符,没有标题,也没有分隔符。以下是 .txt 文件中的几个示例:

4878578572809275874037093859845083594859474905704627402739385785748756 0934893758795493758745846784678576857458708476968983984980985974687586 3989458476857609379087685796847586770493706759787398499485957658968590

我想知道如何根据变量在 R 中分离这些字符。因此,我想将前 3 个数字用于变量 1,接下来的 5 个数字用于变量 2,接下来的 2 个数字用于变量 3,依此类推。

是否有我可以在 R 中使用的表达式,它允许我根据每个变量所需的字符数来分隔 .txt 文件中的观察结果?

我试过 read.fwf 但没有用。或者,也许我尝试不正确。

对此问题的帮助将不胜感激!

4

2 回答 2

1

更好的解决方案

library(utils)
raw <- "4878578572809275874037093859845083594859474905704627402739385785748756
0934893758795493758745846784678576857458708476968983984980985974687586
3989458476857609379087685796847586770493706759787398499485957658968590"

# Put your data in a temporary file.  You shouldn't have to do this, you data
# is already sitting in a file.
ff <- tempfile()
cat(file = ff, raw)

现在读回来read.fwf

answer <-  suppressWarnings(
  read.fwf(ff, widths = c(3, 5, 2)))
# Remember to clean up after ourselves.
unlink(ff)  # Again, you won't need to do this; your file isn't temporary.

answer    
   V1    V2 V3
1 487 85785 72
2  93 48937 58
3 398 94584 76

使用正则表达式的初始答案

您可以使用正则表达式(正则表达式)。我已经编码了您在帖子中所说的位置中断:

library(tidyverse)
library(readr)
byRegx <- function(raw){
  rawSpl <- str_match(raw[1], "(?x) (^\\d{3}) (\\d{5}) (\\d{2}) (.+)")[1,]
  tibble(apples = rawSpl[2], bananas = rawSpl[3], carrots = rawSpl[4], 
         therestofthem = rawSpl[5])
}

将您的输入读入表格,然后应用该byRegex功能

inputTbl<- tibble(
            raw = readr::read_lines("4878578572809275874037093859845083594859474905704627402739385785748756
                     0934893758795493758745846784678576857458708476968983984980985974687586
                     3989458476857609379087685796847586770493706759787398499485957658968590")) %>% 
  mutate(morecol = map(str_trim(raw), byRegx)) %>% 
  unnest() %>% 
  select(- raw)

inputTbl
# A tibble: 3 x 4
# apples bananas carrots therestofthem                                               
# <chr>  <chr>   <chr>   <chr>                                                       
# 1 487    85785   72      809275874037093859845083594859474905704627402739385785748756
# 2 093    48937   58      795493758745846784678576857458708476968983984980985974687586
# 3 398    94584   76      857609379087685796847586770493706759787398499485957658968590
于 2020-05-16T21:39:18.273 回答
0

您可以使用 substring 函数。

txt <- "487857857280927587403709385984508359485947490570462740273938578574875609348937587954937587458467846785768574587084769689839849809859746875863989458476857609379087685796847586770493706759787398499485957658968590"

select <-  c(3 , 5, 2)  # vector of number of words to be extracted

out <- as.numeric(substring(txt, 
                            cumsum(c(1, select[-length(select)])), 
                            cumsum(select)))
out
#[1]   487 85785    72
于 2020-05-16T21:22:52.427 回答