[英]R Sequence of numbers to a dataframe
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: 我有一个包含许多行的数据框,我想添加一个沿第x行计数的列,并相应地对其进行标记,例如:
ROW LABEL
1 1
2 1
3 1
4 1
5 2
6 2
7 2
8 2
9 3
9 3
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). 依此类推,其中ROW是我的数据帧的行。我希望能够更改LABEL计数,在示例中,我已将标签计数设置为4(每第4行将标签递增)。 Any help appreciated.
任何帮助表示赞赏。
P. P.
Two words: integer division . 两个字: 整数除法 。
Using rep()
: 使用
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
Using seq()
: 使用
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
Data 数据
df <- data.frame(ROW=c(1L,2L,3L,4L,5L,6L,7L,8L,9L));
You can use rep
together with the each argument: 您可以将
rep
与每个参数一起使用:
rep(1:4, each=4)
[1] 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4
Then to assign it: 然后进行分配:
df$label <- rep(1:4, each=4)
To get this to be more dynamic, you can feed the x argument a measure of the total rows: 为了使它更具动态性,可以为x参数提供总行数的度量:
df$label <- rep(1:ceiling(nrow(df) / 4), each=4)
This assumes that the total number of rows are divisible by 4. If they are not, you can also include the length.out argument (as suggested by @Frank) to set the correct the length difference: 假设总行数可被4整除。如果不能,则还可以包括length.out参数(如@Frank所建议)以设置正确的长度差:
df$label <- rep(1:ceiling(nrow(df) / 4), each=4, length.out=nrow(df))
It is also possible to feed rep a vector of different lengths to repeat each element in x if you want to vary the lengths of each label. 如果您想改变每个标签的长度,也可以输入不同长度的rep向量来重复x中的每个元素。 For example:
例如:
rep(1:4, c(1, 2, 3, 4))
[1] 1 2 2 3 3 3 4 4 4 4
note that the length vector must have the same length as the x vector. 请注意,长度向量必须与x向量具有相同的长度。
You could use the following code. 您可以使用以下代码。 You can change the number of labels and repetitions in the first two lines.
您可以在前两行中更改标签和重复的数量。
labelQuantity <- 4
repeatLabel <- 4
label <- rep(1:labelQuantity,1,each=repeatLabel)
row <- seq(1,length(label),1)
myDataFrame <- as.data.frame(cbind(row,label))
Cheers! 干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.