从数字范围中获取数字列表 [英] Get a list of numbers from range(s) of number

查看:22
本文介绍了从数字范围中获取数字列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,其中一列包含一个(或多个)数字范围.我想把它变成一个基于给定范围的数字列表.

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.

示例输入:

"35-40"

"35-43, 45-47"

这应该产生:

[1]  35 36 37 38 39 40

[1]  35 36 37 38 39 40 41 42 43 45 46 47

推荐答案

我们可以做一个拆分,用 Map,得到数字

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

数据

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

这篇关于从数字范围中获取数字列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆