如何将一系列循环计算放入向量中

  • 本文关键字:向量 计算 循环 一系列 r
  • 更新时间 :
  • 英文 :


>我生成了以下代码,并希望将 for 循环计算的五个值放入单个向量中。我花了几个小时搜索各种网站,但没有找到任何可以让我这样做的东西。

> complete<-function(directory,ID){
+ files_list <- list.files( directory , full.names=TRUE) #creates a list of files
+ dat <- data.frame() #creates an empty data frame
+ for (i in 1:332) { #loops through the files, rbinding them together
+   dat <- rbind(dat, read.csv(files_list[i]))
+ }
+ cleandat<-na.omit(dat)
+ for(i in ID){
+ n<-nrow(cleandat[cleandat$ID %in% i,])
+ print(n)
+ }
+  
+ #return(ndat)
+ }
> complete("specdata", ID<-c(2,4,8,10,12))
[1] 1041
[1] 474
[1] 192
[1] 148
[1] 96

提前致谢

不要使用 print ,只需将最终结果收集在一起并return

complete<-function(directory,ID){
result<- rep(NA,length(ID))
files_list <- list.files( directory , full.names=TRUE) #creates a list of files
dat <- data.frame() #creates an empty data frame
for (i in 1:332) { #loops through the files, rbinding them together
dat <- rbind(dat, read.csv(files_list[i]))
}
cleandat<-na.omit(dat)
for(i in ID){
n<-nrow(cleandat[cleandat$ID %in% i,])
result[i]<-n
}  
return(result)
}

这将比 for 循环更快、更容易(尽管我担心你会因此丢弃包含所有数据的 dat 对象(:

result <- table(dat$ID)[ID]

建议使用return是不必要的。上次计算的结果会自动从函数返回。如果你想把它打印为副作用,那么print函数(与cat函数不同(也会返回它的参数,所以可以自由地print(. <- .)赋值。

最新更新