逐行读取一个 txt 文件,每隔一行使用 skip 函数,并使用 R 将输出保存为数据帧

Reading a txt file line by line with skip function of every second line and the output saved as a dataframe using R

如能帮助我逐行阅读文本文件并跳过行 (1,3,5,7),我将不胜感激。

输入文件如下所示:

>Q5W0Q7|5-5|ength_1092  
DMESPVFAFPKALDLETHIEKLFLY
>Q6PEW1|2-2|length_402 
DDTLDDSDEDDIVVESQDPPLPSWG
>O43474|1-1|length_513 
PRRETEEFNDLKALDFILSNSLTHP
>Q9UGC6|1-2|length_210 
EKARMIYEDDETYLSPKEVSLDSRV

我想保留第 2、4、6、8 个。像这样:

DMESPVFAFPKALDLETHIEKLFLY 
DDTLDDSDEDDIVVESQDPPLPSWG 
PRRETEEFNDLKALDFILSNSLTHP 
EKARMIYEDDETYLSPKEVSLDSRV

然后,我想将每一行的字符串拆分成单独的字符串。第一个例子:

D M E S P V F A F P K A L D L E T H I E K L F L Y

然后,每一行将单独保存在一个数据框中。前两个的例子:

 df1 <- df(col1 = c('D', 'M' ,'E', 'S', 'P', 'V', 'F', 'A', 'F', 'P', 'K', 'A', 'L', 'D', 'L', 'E', 'T' ,'H', 'I', 'E', 'K' ,'L', 'F', 'L', 'Y'),
col2 = c('D','D','T','L','D','D','S','D','E','D','D','I','V','V','E','S','Q','D','P','P','L','P','S','W','G'))

我想到了这样的方法:(但它不起作用)

df1 <- n.readLines(paste("example1.txt"),
          header = FALSE,
          n = 1, 
         skip =1,3,5,7) %>% #doesn't skip
         res_try <- strsplit(df1, "")[[1]] %>% 
view(df1)

提前感谢您的帮助!

按照建议,我将输入作为列表。

行 <- readLines('example1.txt') lst1 <- strsplit(gsub("\t", "", lines[c(TRUE, FALSE)]), "")

# changed a list into a data frame
dftry <- data.frame(matrix(unlist(lst1), nrow=length(lst1), byrow=T))
# transposed the data frame 
df_trial <- as.data.frame(t(dftry))
df_trial$myfactor <- factor(row.names(dftry))
view(df_trial)

这里的问题是最后一行是 18 而序列是 24 个字母长。有什么建议吗?

我们用readLines

读取数据
lines <- readLines('file.txt')

然后使用逻辑值递归索引并将其拆分为list

lst1 <- strsplit(gsub("\t", "", lines[c(FALSE, TRUE)]), "")
lst1
#[[1]]
# [1] "D" "M" "E" "S" "P" "V" "F" "A" "F" "P" "K" "A" "L" "D" "L" "E" "T" "H" "I" "E" "K" "L" "F" "L" "Y"

#[[2]]
# [1] "D" "D" "T" "L" "D" "D" "S" "D" "E" "D" "D" "I" "V" "V" "E" "S" "Q" "D" "P" "P" "L" "P" "S" "W" "G"

#[[3]]
# [1] "P" "R" "R" "E" "T" "E" "E" "F" "N" "D" "L" "K" "A" "L" "D" "F" "I" "L" "S" "N" "S" "L" "T" "H" "P"

#[[4]]
# [1] "E" "K" "A" "R" "M" "I" "Y" "E" "D" "D" "E" "T" "Y" "L" "S" "P" "K" "E" "V" "S" "L" "D" "S" "R" "V"