Get a list of numbers from range(s) of number

后端 未结 3 1368
青春惊慌失措
青春惊慌失措 2021-01-21 00:31

I have a data frame where one column contains a range (or ranges) of numbers. I would like to turn this into a list of numbers based of the given range.

Example input:

3条回答
  •  野性不改
    2021-01-21 01:16

    We can do a split and with Map, get the numbers

    do.call(Map, c(`:`, lapply(strsplit(df1$v1, '-'), as.numeric)))
    #[[1]]
    # [1] 35 36 37 38 39 40 41 42 43 44 45
    
    #[[2]]
    #[1] 43 44 45 46 47
    

    If we need to find the sequence within the string

    lapply(strsplit(df1$v1, "-"), function(x) Reduce(`:`, as.numeric(x)))
    #[1]]
    #[1] 35 36 37 38 39 40 41 42 43
    
    #[[2]]
    #[1] 45 46 47
    

    Update

    If we have multiple elements in a string

    df1 <- structure(list(v1 = c("35-43", "45-47", "30-42, 25-27")), 
    .Names = "v1", row.names = c(NA, 
     -3L), class = "data.frame")
    
    lapply(strsplit(df1$v1, ", "), function(x) do.call(c, 
        lapply(strsplit(x, "-"), function(y) Reduce(`:`, as.numeric(y)))))
    

    data

    df1 <- structure(list(v1 = c("35-43", "45-47")), .Names = "v1", row.names = c(NA, 
    -2L), class = "data.frame")
    

提交回复
热议问题