【发布时间】:2021-01-22 09:04:38
【问题描述】:
我是 R 的初学者,并且一直在编译代码以创建自定义函数,以对我拥有的某些数据执行特定任务。自定义函数的结构是为了识别 csv 文件中的缺失数据并使用平均值对其进行修补。此后,我想按年和月汇总数据并将其导出为 csv 文件。我有多个 csv 文件位于一个文件夹中,并希望对这些文件中的每一个执行此任务。到目前为止,我能够获得执行手头任务的代码,但不知道如何为每个已处理的 csv 文件编写唯一的输出并将它们保存到新文件夹中。我还想在处理后的输出中保留原始文件名,但要附加“_processed”字样。此外,非常欢迎有关如何改进此代码的任何建议。提前致谢。
# Load all packages required by the script
library(tidyverse) # data science package
library(lubridate) # work with dates
library(dplyr) # data manipulation (filter, summarize, mutate)
library(ggplot2) # graphics
library(gridExtra) # tile several plots next to each other
library(scales)
# Set the working directory #
setwd("H:/Shaeden_Post_Doc/Genus_Exchange/GEE_Data/MODIS_Product_Data_Raw/Cold_Temperate_Moist")
#create a function to summarize data by year and month
#patch missing values using the average
summarize_by_month = function(df){
# counting unique, missing and mean values in the ET column
df %>% summarise(n = n_distinct(ET),
na = sum(is.na(ET)),
med = mean(ET, na.rm = TRUE))
# assign mean values to the missing data and modify the dataframe
df = df %>%
mutate(ET = replace(ET,is.na(ET),mean(ET, na.rm = TRUE)))
df
#separate data into year, month and day
df$date = as.Date(df$date,format="%Y/%m/%d")
#summarize by year and month
df %>%
mutate(year = format(date, "%Y"), month = format(date, "%m")) %>%
group_by(year, month) %>%
summarise(mean_monthly = mean(ET))
}
#import all files and execute custom function for each
file_list = list.files(pattern="AET", full.names=TRUE)
file_list
my_AET_files = lapply(file_list, read_csv)
monthly_AET = lapply(my_AET_files, summarize_by_month)
monthly_AET
下面提供了示例数据集的链接 https://drive.google.com/drive/folders/1pLHt-vT87lxzW2We-AS1PwVcne3ALP2d?usp=sharing
【问题讨论】: