Search code examples
rlistdataframerowcol

R - remove last row and convert row in column in dataframes within a list


I need your help as I have to:

  • remove the last row in all my dataframes contained in a list and
  • add a new column to all the dataframes which contains the first row value of them.

Here an example of one of my dataframes:

         V1        V2        V3
2         7002                    
8  14 Feb 1959    47.664     1.310
9  25 Aug 1960   680.615     3.790
10 08 Aug 1961   287.893     2.490
11 11 Feb 1962   405.366     2.920
12 14 Dec 1962   312.010     2.560
13 18 Aug 1964   167.684     1.930

    [....]

53 19 Jan 2004   385.980     2.835
54 13 Jun 2005   415.942     2.939
55 26 Nov 2005   280.773     2.431
56       [END]     

So, in this case, add 7002 as new column and remove the 56th row. I have got ~290 dataframes in my list.

Thanks Paolo


Solution

  • We can use lapply to loop over the list, remove the last row (x[-nrow(x),]), and create a new column with the first cell value.

    lst1 <- lapply(lst, function(x) transform(x[-nrow(x),], NewCol = x[1,1]))