readStateData <- function() {
infile <- paste("state",i,".txt",sep="")
state <- readLines(infile,n=1)
statedata <- read.table(infile,header=FALSE,sep=",",skip=1,col.names=c("Rank","City","Population"))
statename <- list(state,statedata)
statename
}
# Start loop
for(i in 1:50) {
readStateData()
# Add function to big.list
big.list[[i]] <- readStateData(statename)
}
类的赋值是引入50个文件,所有名为state#.txt,通过readLines获取状态,通过read.table获取数据,最后将它们全部放入big.list中所有数据都通过for循环。
我遇到的问题是在for循环期间调用该函数。我收到错误:
Error in readStateData(statename) : unused argument (statename)
我要么没有正确地调用该功能,要么我写错了该功能。两者都有可能。
感谢您的帮助。
答案 0 :(得分:0)
这里有不同的问题。
不要在函数内部引用外部定义的变量。它意味着代替在函数内部定义i
的函数外部:
i <- 1
fct <- function() {
a <- i + 1
return(a)
}
fct()
将变量作为参数传递给函数:
i <- 1
fct <- function(x) {
a <- x + 1
return(a)
}
fct(i)
在您的函数中,缺少return语句。请参见函数中最后一个命令的第1点。如果没有return语句,最后写入的变量将在堆栈中并由函数“返回”。这不是返回值的干净方法。
你的代码看起来应该是这样的
readStateData <- function(x) {
infile <- paste("state",x,".txt",sep="")
state <- readLines(infile,n=1)
statedata <-read.table(infile,header=FALSE,sep=",",skip=1,col.names=c("Rank","City","Population"))
statename <- list(state,statedata)
return(statename)
}
# Start loop
for(i in 1:50) {
j <- readStateData(i)
# Add function to big.list
big.list[[i]] <- j
}
如果您的文件都是模式:state [number] .txt,您可以将代码简化为:
# Get all files with pattern state*.txt
fls <- dir(pattern='state.*txt')
readStateData <- function(x) {
state <- readLines(x, n=1)
statedata <-read.table(x, header=FALSE,sep=",",skip=1,col.names=c("Rank","City","Population"))
statename <- list(state,statedata)
return(statename)
}
# Start loop
for(i in 1:length(fls)) {
j <- readStateData(fls[i])
# Add function to big.list
big.list[[i]] <- j
}