![](/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.