Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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 :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading