简体   繁体   中英

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:

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). Any help appreciated.

P.

Two words: integer division .

Using 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() :

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(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:

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:

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM