I'm trying to remove the same number of rows from multiple (28) dataframes, each of varying length. Here's a toy dataset to illustrate what I mean:
df1 <- data.frame(
var1 = c(1,2,3,4,5),
var2 = c(2,4,6,8,10)
)
df2 <- data.frame(
var3 = c(1,2,3,4,5,6,7),
var4 = c(2,4,6,8,10,12,14)
)
df3 <- data.frame(
var5 = c(1,2,3,4,5,6,7,8,9,10),
var6 = c(2,4,6,8,10,12,14,16,18,20)
)
I've written a function (below) to do this, which works on individual dataframes:
remove_rows <- function(x){
x[c(3:nrow(x)),]
}
I've then created a list of the dataframes using df_list <- ls()
and tried to run the function across each item in the list using lapply(df_list, function(x) remove_rows(x))
, but I keep getting this error: Error in 3:nrow(x) : argument of length 0
.
I think it's because my function is trying to act on the item within my list, as opposed to the data frame which the name of the item in my list represents, but I can't work out how to alter it.
I've also tried the hacky approach of a for
loop (below), which failed too.
for (i in 1:length(df_list)){
name <- df_list[i]
assign(name, remove_rows(df_list[i]))
}