Home > Mobile >  How can I replace values with the continuous count every n rows in R
How can I replace values with the continuous count every n rows in R

Time:07-10

I am a bit stuck with replacing values. I have a column that counts frames per second. I appended the file but the appended file starts with the frame "1" again in the [12] column below.

So what I need to do is replace the last four frames featuring "1" with "4" and so on. Or in other words, assign a new value to every four rows.

let's say df$frames is:

[,1] 1
[1,] 1 
[2,] 1 
[3,] 1 
[4,] 2 
[5,] 2
[6,] 2 
[7,] 2 
[8,] 3 
[9,] 3 
[10,] 3 
[11,] 3 
[12,] 1
[13,] 1 
[14,] 1
[15,] 1  

A quick hint would help me a lot :D Best :*

CodePudding user response:

I'm not sure I understand the problem; if you have:

df <- data.frame(frames = c(rep(1:3, each = 4), rep(1, 4)))
df
#>    frames
#> 1       1
#> 2       1
#> 3       1
#> 4       1
#> 5       2
#> 6       2
#> 7       2
#> 8       2
#> 9       3
#> 10      3
#> 11      3
#> 12      3
#> 13      1
#> 14      1
#> 15      1
#> 16      1

Created on 2022-07-09 by the reprex package (v2.0.1)

And you want :

df <- data.frame(frames = c(rep(1:4, each = 4)))
df
#>    frames
#> 1       1
#> 2       1
#> 3       1
#> 4       1
#> 5       2
#> 6       2
#> 7       2
#> 8       2
#> 9       3
#> 10      3
#> 11      3
#> 12      3
#> 13      4
#> 14      4
#> 15      4
#> 16      4

Created on 2022-07-09 by the reprex package (v2.0.1)

You can change the value of the last 4 rows:

df <- data.frame(frames = c(rep(1:3, each = 4), rep(1, 4)))
df
#>    frames
#> 1       1
#> 2       1
#> 3       1
#> 4       1
#> 5       2
#> 6       2
#> 7       2
#> 8       2
#> 9       3
#> 10      3
#> 11      3
#> 12      3
#> 13      1
#> 14      1
#> 15      1
#> 16      1
df[(nrow(df)-3):nrow(df),] <- 4
df
#>    frames
#> 1       1
#> 2       1
#> 3       1
#> 4       1
#> 5       2
#> 6       2
#> 7       2
#> 8       2
#> 9       3
#> 10      3
#> 11      3
#> 12      3
#> 13      4
#> 14      4
#> 15      4
#> 16      4

Created on 2022-07-09 by the reprex package (v2.0.1)

Or you can change the value of every 4 rows using rep(), e.g.:

df <- data.frame(frames = c(rep(1:6, each = 4)))
df
#>    frames
#> 1       1
#> 2       1
#> 3       1
#> 4       1
#> 5       2
#> 6       2
#> 7       2
#> 8       2
#> 9       3
#> 10      3
#> 11      3
#> 12      3
#> 13      4
#> 14      4
#> 15      4
#> 16      4
#> 17      5
#> 18      5
#> 19      5
#> 20      5
#> 21      6
#> 22      6
#> 23      6
#> 24      6

Created on 2022-07-09 by the reprex package (v2.0.1)

Or is there something I'm missing?

  •  Tags:  
  • r
  • Related