R: how to get information from a txt file with R

穿精又带淫゛_ 提交于 2019-12-06 07:48:58

To answer your first question, to read a text file you should use the function scan(). The references you see on SO to textConnection are purely to read in some example data that is pasted into the console. This is what I am doing next to read your data:

txt <- "
x1 `xx`nkkna`yy`taktnaknvcaklrhkahnktn, altlkhakthakd`xx`nmm  cataitha`yy`knkcnaktnhakt
x2 `xx`ngkna`yy`taktnaknvcaklrhkahnktn, altlkhakthakdnmm  cataithaknkcnaktnhakt 
x3 `xx`nkg,kna`yy`taktnaknvcaklrhkahnktn, altlkhakthakdnmm  cataithaknk`xx`cna`yy`ktnhakt 
x4  nkkndataktnaknvcaklrhkahnktn, altlkhakthakdnmm  cataithaknkcnaktnhakt"

dtxt <- textConnection(txt)

Then I use scan in the same way to read the textConnetion data. In your own code, you should modify the following line, so tat dtxt is your file location. I keep it in this format, so that other people can replicate my results without having to create a file on their own file system:

dat <- scan(dtxt, what="character", sep="\n")

Now that you have read the data, it is a (somewhat complicated) call to sapply, strsplit and gsub to manipulate the data.

sapply(seq_along(dat), 
    function(i)unlist(c(sapply(strsplit(dat[i], "`xx`"), 
              function(x)gsub("^(.*?)`.*", "\\1", x)[-1]))))

The results are exactly as you specified:

[[1]]
[1] "nkkna"         "nmm  cataitha"

[[2]]
[1] "ngkna"

[[3]]
[1] "nkg,kna" "cna"    

[[4]]
character(0)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!