'Create new columns for last n rows in dataframe by group dplyr

I have the following data frame:

df <- data.frame(
  ID  =  c(11041,11041,11041,11041,11041,11041,11042,11042,11042,11063,11063),
  p = c(2.9,3.6,4.8,2.6,2.2,3.9,6.5,2.9,1.4,0.7,5.1)
    )

Which gives this output:

      ID   p
1  11041 2.9
2  11041 3.6
3  11041 4.8
4  11041 2.6
5  11041 2.2
6  11041 3.9
7  11042 6.5
8  11042 2.9
9  11042 1.4
10 11063 0.7
11 11063 5.1

I am trying to create new columns for the last n values (let's say 3) by ID, so my new data frame would look like so:

      ID   p p1.1 p1.2 p1.3
1  11041 2.9   NA   NA  2.9
2  11041 3.6   NA  2.9  3.6
3  11041 4.8  2.9  3.6  4.8
4  11041 2.6  3.6  4.8  2.6
5  11041 2.2  4.8  2.6  2.2
6  11041 3.9  2.6  2.2  3.9
7  11042 6.5   NA   NA  6.5
8  11042 2.9   NA  6.5  2.9
9  11042 1.4  6.5  2.9  1.4
10 11063 0.7   NA   NA  0.7
11 11063 5.1   NA  0.7  5.1

Ideally, I would like to be able to specify the last n values, so that if I want the last 5 (creating p.1, p.2, p.3, p.4, p.5) I can do this. But n could be any number, like 3,5,10,15, etc.

With dplyr, I have tried both spread and pivot_wider but could not get them to work.



Solution 1:[1]

Try to change "Router" to "Routes". Also use "exact" in the "Route"-Component.

I always do it like that.

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import { Home } from './components/home/Home';

...

<Router>
  <Routes>
    <Route path="/" exact element={<Home></Home>} />
  </Routes>
</Router>
...

If this doesn't help you can maybe find your solution here: https://reactjs.org/warnings/invalid-hook-call-warning.html#:~:text=Hooks%20can%20only%20be%20called,of%20React%20and%20React%20DOM.&text=You%20might%20have%20more%20than,React%20in%20the%20same%20app.

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