Reputation:
I need your help as I have to:
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
Upvotes: 1
Views: 1430
Reputation: 1692
If all your dataframes look the same you could use something similar to that:
df1 <- data.frame(matrix(data = (rnorm(9)), 3, 3))
df2 <- data.frame(matrix(data = (100:108), 3, 3))
colnames(df1) <- c("V1", "v2", "V3")
colnames(df2) <- c("V1", "v2", "V3")
list1 <- list(df1, df2)
list2 <- list1
for(i in 1:length(list2)) {
list2[[i]] <- list2[[i]][-length(list2[[i]]), ]
colnumber <- dim(list2[[i]])[2] + 1
list2[[i]]$V4 <- list2[[i]][1, 1]
}
list2
However, if you have a more complicated structure or the values are not in the same spot in every dataframe, you will have to look for a dplyr or apply-solution or even write your own function for doing so.
I hope it helps.
Upvotes: 0
Reputation: 887148
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]))
Upvotes: 3