首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何折叠R中整数序列中的空隙?

如何折叠R中整数序列中的空隙?
EN

Stack Overflow用户
提问于 2022-09-12 13:19:56
回答 1查看 50关注 0票数 1

是否有一个方便的基R或包函数,用于折叠,或插值,在任何间隙之间的整数值的数字序列?我已经搜索过像dplyr::dense_rank这样的函数,但是在这种情况下,它们不起作用。下面的代码生成一个示例,在单个列(column =Grp)中开始编号序列:

代码语言:javascript
复制
> myDF <- data.frame(Grp = c(1,2.1,2.2,4.1,4.2,6.1,9))
> myDF   
  Grp
1 1.0    
2 2.1    
3 2.2    
4 4.1
5 4.2
6 6.1
7 9.0

下面是我想要更改输出的方式;下面我手动在每个Grp行的右侧添加一个列的值(“折叠”),解释我试图导出的内容:

代码语言:javascript
复制
    > myDF   
      Grp    Collapse 
    1 1.0    Every sequence starts with 1 so leave Grp as is
    2 2.1    Integer gap between rows 1-2 is <= 1 so leave Grp as is
    3 2.2    Integer gap between rows 2-3 is <= 1 so leave Grp as is
    4 3.0    Integer gap between original rows 3-4 is not <= 1 so fill in the gap with the seq integer 
    5 4.1    Integer gap between rows 4-5 is <= 1 so leave Grp as is
    6 4.2    Integer gap between rows 5-6 is <= 1 so leave Grp as is
    7 5.0    Integer gap between original rows 5-6 is not <= 1 so fill in the gap with the seq integer 
    8 6.1    Integer gap between row 7-8 is <= 1 so leave Grp as is
    9 7.0    Integer gap between original rows 6-7 is not <= 1 so fill in the gap with the seq integer
   10 8.0    Integer gap between original rows 6-7 is not <= 1 so fill in the gap with the seq integer
   11 9.0    Integer gap between row 10-11 is <= 1 so leave Grp as is
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-12 13:29:09

你可以:

代码语言:javascript
复制
f <- floor(myDF$Grp)
s <- seq(min(f), max(f))
sort(c(myDF$Grp, s[!s %in% f]))
#[1] 1.0 2.1 2.2 3.0 4.1 4.2 5.0 6.1 7.0 8.0 9.0
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73690012

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档