R数据框的数字序列 [英] R Sequence of numbers to a dataframe

查看:59
本文介绍了R数据框的数字序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含很多行的数据框,我想添加一个沿第x行计数的列并相应地对其进行标记,例如:

I have a Dataframe with many rows, I'd like to add a column that counts along every xth row and label it accordingly, for example:

ROW    LABEL
1      1
2      1
3      1
4      1
5      2
6      2
7      2
8      2
9      3
9      3

,其中ROW是我的数据帧的行。我希望能够更改LABEL计数,在示例中,我已将标签计数设置为4(每第4行使标签递增)。
任何帮助表示赞赏。

And so on, where ROW is the row of my Dataframe .I'd like to be able to alter the LABEL count, in the example I have shown the label count is set to 4 (every 4th row increment the label). Any help appreciated.

P。

推荐答案

两个词:整数除法

使用 rep()

N <- 4L; df$LABEL <- rep(seq_len(nrow(df)%/%N+1L),each=N,len=nrow(df));
df;
##   ROW LABEL
## 1   1     1
## 2   2     1
## 3   3     1
## 4   4     1
## 5   5     2
## 6   6     2
## 7   7     2
## 8   8     2
## 9   9     3

使用 seq()

N <- 4L; df$LABEL <- seq(0L,len=nrow(df))%/%N+1L;
df;
##   ROW LABEL
## 1   1     1
## 2   2     1
## 3   3     1
## 4   4     1
## 5   5     2
## 6   6     2
## 7   7     2
## 8   8     2
## 9   9     3






数据

df <- data.frame(ROW=c(1L,2L,3L,4L,5L,6L,7L,8L,9L));

这篇关于R数据框的数字序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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