[英]Is there a function in R to separate .txt files with no delimiter?
我得到了一个 .txt 格式的数据集,我需要将其导入 R 进行研究分析。 .txt 文件有一列带有数字字符,没有 header,也没有分隔符。 以下是 .txt 文件中的几个示例:
4878578572809275874037093859845083594859474905704627402739385785748756 0934893758795493758745846784678576857458708476968983984980985974687586 3989458476857609379087685796847586770493706759787398499485957658968590
我想知道如何根据其变量将 R 中的这些字符分开。 因此,我想将前 3 个数字用于变量 1,接下来的 5 个数字用于变量 2,接下来的 2 个数字用于变量 3,依此类推。
是否有我可以在 R 中使用的表达式,它允许我根据每个变量所需的字符数分隔 .txt 文件中的观察结果?
我试过 read.fwf 但没有用。 或者,也许我尝试不正确。
对此问题的帮助将不胜感激!
您可以使用 substring function。
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
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
您可以使用正则表达式(正则表达式)。 我已经编码了 position 中断,您在帖子中说:
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
function
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.