Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a new column using the values of the next n rows?

Tags:

r

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.

like image 779
Samet Sökel Avatar asked Oct 17 '25 17:10

Samet Sökel


2 Answers

You could just apply across all the rows, ensuring your desired length doesn't overrun the number of rows and paste together.

n <- nrow(df)

df$des_column <- sapply(
  1:n,
  \(x) paste(df$a[x:min(x+parm-1, n)], collapse = ",")
)

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

\(x) is shorthand for function(x) released in R 4.1

like image 151
caldwellst Avatar answered Oct 20 '25 08:10

caldwellst


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
like image 27
PaulS Avatar answered Oct 20 '25 07:10

PaulS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!