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

521 views Asked by At

I would be grateful for some help with reading a text file line by line and skipping lines (1,3,5,7).

The input file looks like this:

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

I want to keep just likes 2nd, 4th, 6th, 8th. Like this:

DMESPVFAFPKALDLETHIEKLFLY 
DDTLDDSDEDDIVVESQDPPLPSWG 
PRRETEEFNDLKALDFILSNSLTHP 
EKARMIYEDDETYLSPKEVSLDSRV

Then, I want to split the string from each line into separate strings. The example for the first one:

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

Then, each line would be saved separately in a single data frame. The example for the first two:

 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'))

I came up with something like this: (but it doesn't work)

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)

Thank you for your help in advance!

As suggested, I put the input as a list.

lines <- 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)

Here the problem is that the last row is 18 while the sequence is 24 letters long. Any suggestions?

1

There are 1 answers

4
akrun On BEST ANSWER

We read the data with readLines

lines <- readLines('file.txt')

Then use a recursive indexing with logical value and split it to a 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"