在您的代码中,当您通过 TRUE 来汇总时,它绕过了 return(c) 语句,因此 R 决定返回汇总。由于您想为所有情况返回数据框 c,您只需将其放在 if/else 结构之外。
将您的 if/else 结构修改为:
getmonitor<- function(id,directory,summarize=FALSE) {
a<- "C:/Users/UNI/Documents/Coursera/archivosR/"
b<- paste(a,directory,"/",sprintf("%03d",as.numeric(id)),".csv",sep="")
c<- read.csv(b)
if(summarize)
print(summary(c))
return(c)
}
给了我想要的输出:
> data <- getmonitor(1,"specdata",TRUE)
Date sulfate nitrate ID
2003-01-01: 1 Min. : 0.613 Min. :0.1180 Min. :1
2003-01-02: 1 1st Qu.: 2.210 1st Qu.:0.2835 1st Qu.:1
2003-01-03: 1 Median : 2.870 Median :0.4530 Median :1
2003-01-04: 1 Mean : 3.881 Mean :0.5499 Mean :1
2003-01-05: 1 3rd Qu.: 4.730 3rd Qu.:0.6635 3rd Qu.:1
2003-01-06: 1 Max. :19.100 Max. :1.8300 Max. :1
(Other) :1455 NA's :1344 NA's :1339
> head(data)
Date sulfate nitrate ID
1 2003-01-01 NA NA 1
2 2003-01-02 NA NA 1
3 2003-01-03 NA NA 1
4 2003-01-04 NA NA 1
5 2003-01-05 NA NA 1
6 2003-01-06 NA NA 1