'How to create a new column using the values of the next n rows?
I have a data.frame object and a parameter parm which represents how many lines after it will be used with itself.
data is looking so;
parm <- 3
df <- data.frame(a=LETTERS[1:5])
df
a
<chr>
1 A
2 B
3 C
4 D
5 E
The number of rows to be used should be reduced if not possible, If I need to explain it with the desired output;
a des_column
<chr> <chr>
1 A A,B,C
2 B B,C,D
3 C C,D,E
4 D D,E
5 E E
base R functions would be much better.
Thanks in advance.
Solution 1:[1]
Another possible solution, based on zoo::rollapply:
library(zoo)
parm <- 3
df <- data.frame(a=LETTERS[1:5])
df$des_column <- rollapply(df$a, parm, paste, collapse = ",",
partial=T, align="left")
df
#> a des_column
#> 1 A A,B,C
#> 2 B B,C,D
#> 3 C C,D,E
#> 4 D D,E
#> 5 E E
Solution 2:[2]
Using the same logic from above, another way would be:
library(tidyverse)
df$des_column <- map_chr(seq_len(nrow(df)),
function(i) glue_collapse(df$a[i:min(i+parm-1, nrow(df))], sep = ','))
#> a des_column
#> 1 A A,B,C
#> 2 B B,C,D
#> 3 C C,D,E
#> 4 D D,E
#> 5 E E
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | AlexB |
