Reputation: 35
I got a txt file in this way:
-- SMART RESULTS TEXTFORMAT --
USER_PROTEIN_ID = SAUSA300_RS14200
SMART_PROTEIN_ID = uniprot|Q5HCS9|Q5HCS9_STAAC
NUMBER_OF_FEATURES_FOUND=1
DOMAIN=transmembrane_domain
START=7
END=29
EVALUE=0
TYPE=INTRINSIC
STATUS=visible|OK
-- FINISHED --
-- SMART RESULTS TEXTFORMAT --
USER_PROTEIN_ID = SAUSA300_RS11975
SMART_PROTEIN_ID = uniprot|A6QJ58|A6QJ58_STAAE
NUMBER_OF_FEATURES_FOUND=0
-- FINISHED --
-- SMART RESULTS TEXTFORMAT --
USER_PROTEIN_ID = SAUSA300_RS14395
SMART_PROTEIN_ID = uniprot|Q2FDK5|SRAP_STAA3
NUMBER_OF_FEATURES_FOUND=1
DOMAIN=Pfam:Gram_pos_anchor
START=2221
END=2258
EVALUE=6e-08
TYPE=PFAM
STATUS=visible|OK
-- FINISHED --
What I want is to get information between "SMART RESULTS TEXTFORMAT" and "FINISHED" and export each part for different USER_PROTEIN_ID into each row in table.
Could any one provide some codes? I got some complicated ones by myself. It ended up in a dataframe, but don't know how to continue to export to each row in excel.
start="-- SMART RESULTS TEXTFORMAT --"
end="-- FINISHED --"
n=nrow(myfile)
index=c(1:n)
myfile=cbind(index,myfile)
starline=as.data.frame(grep(start,myfile[,2]))
endline=as.data.frame(grep(end,myfile[,2]))
indexlist=cbind(starline,endline)
newlist=character(length = n)
for (i in 1:n) {
index1=indexlist[i,1]+1
index2=indexlist[i,2]-1
newlist[i]=as.data.frame(as.data.frame(myfile[index1:index2,2]))
}
Upvotes: 0
Views: 84
Reputation: 12420
I think this should work nicely for you:
library("magrittr")
data <- split(txt, cumsum(grepl("-- SMART RESULTS TEXTFORMAT --", txt))) %>%
lapply(function(i) i[!grepl("-- SMART RESULTS TEXTFORMAT --|-- FINISHED --", i)]) %>%
lapply(function(i) {
read.table(text = i, sep = "=", header = FALSE) %>%
t(.) %>%
tibble::as_tibble() %>%
magrittr::set_colnames(trimws(.[1, ])) %>%
slice(-1)
}) %>%
plyr::rbind.fill()
For export, I would highly recommend rio
:
rio::export(data, "data.xlsx")
Here is how I got the data (I write out the text and read it back it to simulate that part as well):
txt <- "-- SMART RESULTS TEXTFORMAT --
USER_PROTEIN_ID = SAUSA300_RS14200
SMART_PROTEIN_ID = uniprot|Q5HCS9|Q5HCS9_STAAC
NUMBER_OF_FEATURES_FOUND=1
DOMAIN=transmembrane_domain
START=7
END=29
EVALUE=0
TYPE=INTRINSIC
STATUS=visible|OK
-- FINISHED --
-- SMART RESULTS TEXTFORMAT --
USER_PROTEIN_ID = SAUSA300_RS11975
SMART_PROTEIN_ID = uniprot|A6QJ58|A6QJ58_STAAE
NUMBER_OF_FEATURES_FOUND=0
-- FINISHED --
-- SMART RESULTS TEXTFORMAT --
USER_PROTEIN_ID = SAUSA300_RS14395
SMART_PROTEIN_ID = uniprot|Q2FDK5|SRAP_STAA3
NUMBER_OF_FEATURES_FOUND=1
DOMAIN=Pfam:Gram_pos_anchor
START=2221
END=2258
EVALUE=6e-08
TYPE=PFAM
STATUS=visible|OK
-- FINISHED --"
writeLines(txt, "test.txt")
txt <- readLines("test.txt")
Upvotes: 1
Reputation: 408
The code you wrote looks fine.
For the excel export look at the xlsx package
Upvotes: 0