简体   繁体   中英

create list with values between begin and end positions

I have a text file with this format

begin    end   
1        10    
25       35
40       50
37       48
...      ...

I use these commands to make a list that contains all the values that are between the values from 'begin' and 'end' column

x <- read.table("in.txt")

result <- vector("list",486)
      for(i in 1:486){
      result[[i]] <- c(x[i,1]:x[i,2])
      }
lapply(result, write, "out.txt", append=TRUE, ncolumns = 1) 

So as result I get a file with 1 column where all the values are on different lines. Now I want to do something extra.

Instead of an input file with only a 'begin' and 'end' column, I have two extra columns, like this:

begin    end    A    B
1        10     x    0
25       35     x    1
40       50     x    2
37       48     y    0

I want now that the values of these other columns also appear in my output, so that I get something like this

position    A    B
1           X    0
2           X    0
3           X    0
...
10          X    0
...
40          X    2
41          X    2
...
37          Y    0        

How can I change my function, so that the output looks like this?

Here's a data.table solution:

require(data.table)
DT <- data.table(DF, key=c("A", "B"))
DT[, list(pos = seq(begin, end, by=1)),by=key(DT)]

Here's a base answer:

lapply(1:nrow(x), function(u) cbind(position=x$begin[u]:x$end[u], x[u,3:4]))

HTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM