在r中数据框的列中输入没有特定结尾的序列号 [英] input sequential numbers without specific end in a data frame's column in r

查看:126
本文介绍了在r中数据框的列中输入没有特定结尾的序列号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想给数据帧的新列提供一个数字序列.但是,此序列将根据另一列中的值重复几次. (即从1开始,直到该特定值将更改为其他值).

I would like to give a sequence of numbers to a new column to a data frame. But this sequence will repeat several times based on a value in another column. (i.e It starts from 1 until that specific value will be changed to other value).

我的问题是如何为r中的每个序列定义终点.

My problem is how to define the ending point for each sequence in r.

数据框的一部分,我打算添加"V2"列:

A part of my data frame with the column "V2" which I intend to add:

  V1      V2(new added column with sequential numbers)           
  12      1
  12      2
  12      3
  12      4
  12      5
  13      1
  13      2
  13      3
  13      4
  13      5
  13      6
  14      1
  14      2
  14      3
  14      4

我尝试使用下面的代码,该代码不起作用!

I tried to use the following code, which was not working!

count <- table(df$V1)
c <- as.integer(names(count)[df$V1==12])
    repeat{
      df$V2<- seq(1,c, by=1)
      if(df$V1!=12){
        break
      }
    }

推荐答案

听起来好像您正在寻找rle,因为您随时都对"V1"变量更改感兴趣.

It sounds like you might be looking for rle since you're interested in any time the "V1" variable changes.

请尝试以下操作:

> sequence(rle(df$V1)$lengths)
 [1] 1 2 3 4 5 1 2 3 4 5 6 1 2 3 4

这篇关于在r中数据框的列中输入没有特定结尾的序列号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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