以下是我写的程序,
func <- function(id = 1:200)
{
dir_char <- as.character(directory) ### changing directory input to character
set_dir <- paste('C:/Users/Junk/Documents/',dir_char,sep="") ### setting working directory path
setwd(set_dir) ### setting input directory as working directory
count <- 0
for (i in id) ### going through the id values
{
id_char <- as.character(i) ### changing id value to character for setting the file name
new_file <- data.frame(read.csv(paste(id_char,".csv",sep="")))
mod_file <- data.frame(new_file[complete.cases(new_file),])
count <- nrow(mod_file)
print(count)
out_file <- data.frame(id = id, nobs = count)
}
return(out_file)}
此功能的输出如下
[1] 1041
[1] 474
[1] 192
[1] 148
[1] 96
id nobs
1 2 96
2 4 96
3 8 96
4 10 96
5 12 96
为什么数据帧out_file
在每次循环迭代后都没有存储count
值,我期望数据帧将print(count)
值存储到out_file中。我哪里出错了,请帮我解决问题。
答案 0 :(得分:0)
问题在于
`out_file <- data.frame(id = id, nobs = count)`
每个循环都会创建data.frame
。然后返回最后一个。您可以更改逻辑并在data.frame
结束后创建loop
。
解决问题的一种方法是(我修改了功能的相关部分):
func <- function(id = 1:200)
{
dir_char <- as.character(directory) ### changing directory input to character
set_dir <- paste('C:/Users/Junk/Documents/',dir_char,sep="") ### setting working directory path
setwd(set_dir) ### setting input directory as working directory
count <- numeric(length(id))
for (i in id) ### going through the id values
{
### changing id value to character for setting the file name
id_char <- as.character(i)
new_file <- data.frame(read.csv(paste(id_char,".csv",sep="")))
mod_file <- data.frame(new_file[complete.cases(new_file),])
count[i] <- nrow(mod_file)
print(count)
}
out_file <- data.frame(id = id, nobs = count)
return(out_file)
}
答案 1 :(得分:0)
你做错了一些事。在他的回答中,我的"search.location": "sidebar"
部分解释了。循环正在产生问题。此外,我假设您需要一个MKR
一个nobs
。如果是这样,试试这个::
id