![](/img/trans.png)
[英]Creating a new column using mutate which is some function of the contents of a specified set of columns for each row in a data frame (dplyr)
[英]creating a function which extracts a user specified column from a set of files
我有一组csv文件。 它们都具有相同的结构。 我想创建一个从所有文件中提取特定列的函数。 查找该列中所有值的均值,并将其存储在向量中。 列名应由用户传递。
我已经编写了以下程序。 它以某种方式无法识别包含列名称的“污染物”。
pollutantmean<-function(pollutant)
{
file_names<-dir("C:/Users/Keval/Desktop/Project R/R_courseera_programming_exercise/specdata",pattern= glob2rx("*.csv"))
for(file_name in file_names)
{
file_reader<-read.csv(file_name)
pollutant_data<-file_reader$pollutant
}
pollutant_data
pollutant
}`enter code here`
使用字符串,例如,使用
pollutantmean(pollutant = "mercury")
并使用[
(接受字符串)代替$
,而不是:
# replace the line
pollutant_data <- file_reader$pollutant
# with this:
pollutant_data <- file_reader[, pollutant]
这不会出错,但是您仍然需要花一点时间并存储它。 我也很确定你想要list.files
,而不是dir
。
pollutantmean<-function(pollutant) {
file_names <- list.files("C:/Users/Keval/Desktop/ProjectR/R_courseera_programming_exercise/specdata",
pattern= glob2rx("*.csv"))
# initialize mean vector at correct length
my_means = numeric(length(file_names)
# make the loop indexed by number
for(i in seq_along(file_names)) {
file_reader <- read.csv(file_names[i])
pollutant_data <- file_reader[, pollutant]
# using the number index
my_means[i] = mean(pollutant_data)
}
return(my_means)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.