[英]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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.