将用户定义的函数应用于数据框列表

Apply a user defined function to a list of data frames

我有一系列结构类似于此的数据框:

df <- data.frame(x = c('notes','year',1995:2005), y = c(NA,'value',11:21))  
df2 <- data.frame(x = c('notes','year',1995:2005), y = c(NA,'value',50:60))

为了清理它们,我编写了一个带有一组清理步骤的用户定义函数:

clean <- function(df){
  colnames(df) <- df[2,]
  df <- df[grep('^[0-9]{4}', df$year),]
  return(df)
}

我现在想将我的数据框放入列表中:

df_list <- list(df,df2)

然后一次全部清理干净。我试过了

lapply(df_list, clean)

for(df in df_list){
  clean(df)
}

但是用这两种方法我都得到了错误:

Error in df[2, ] : incorrect number of dimensions

是什么导致了这个错误,我该如何解决?我处理这个问题的方法是错误的吗?

你很接近,但代码中有一个问题。由于您的数据框的列中有文本,因此列被创建为因素而不是字符。因此,您的列命名不会提供预期的结果。

#need to specify strings to factors as false
df <- data.frame(x = c('notes','year',1995:2005), y = c(NA,'value',11:21), stringsAsFactors = FALSE)  
df2 <- data.frame(x = c('notes','year',1995:2005), y = c(NA,'value',50:60), stringsAsFactors = FALSE)

clean <- function(df){
  colnames(df) <- df[2,]
  #need to specify the column to select the rows
  df <- df[grep('^[0-9]{4}', df$year),]

  #convert the columns to numeric values
    df[, 1:ncol(df)] <- apply(df[, 1:ncol(df)], 2, as.numeric)

  return(df)
}

df_list <- list(df,df2)
lapply(df_list, clean)