[R] Naming output file

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Mon Jun 24 13:55:32 CEST 2024


Às 12:41 de 24/06/2024, Steven Yen escreveu:
> I would like a loop to
> 
> (1) read data files 2010midata1,2010midata2,2010midata3; and
> 
> (2)  name OUTPUT bop1,bop2,bop3.
> 
> I succeeded in line 3 of the code below,
> 
> BUT not line 4. The error message says:
> 
> Error in paste0("bop", im) <- boprobit(eqs, mydata, wt = weight, method
> = "NR", : target of assignment expands to non-language object Please
> help. Thanks.
> 
> m<-3
> for (im in 1:m) {
> mydata<-read.csv(paste0("2010midata",im,".csv"))
> paste0("bop",im)<-boprobit(eqs,mydata,wt=weight,method="BHHH",tol=0,reltol=0,gradtol=1e-5,Fisher=TRUE)
> }
> 
> 
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
Hello,

Here are two ways, with a for loop and with a lapply loop.


# for loop
m <- 3
# create the input filenames in one instruction
INPUT <- paste0("2010midata", seq.int(m), ".csv")
# create a named list with m elements to store the output
OUTPUT <- vector("list", length = m) |> setNames(paste0("bop", seq.int(m)))
for(i in seq.int(m)) {
   mydata <- read.csv(INPUT[[i]])
   OUTPUT[[i]] <- boprobit(eqs, mydata, wt=weight, method="BHHH",
                           tol=0, reltol=0, gradtol=1e-5, Fisher=TRUE)
}



# lapply loop
m <- 3
# create the input filenames in one instruction
INPUT <- paste0("2010midata", seq.int(m), ".csv")
# no need to create the output list, it will be the
# return value of lapply
OUTPUT <- lapply(INPUT, \(f) {
   mydata <- read.csv(f)
   boprobit(eqs, mydata, wt=weight, method="BHHH",
            tol=0, reltol=0, gradtol=1e-5, Fisher=TRUE)
})
# assign the output list's names
names(OUTPUT) <- paste0("bop", seq.int(m))


Hope this helps,

Rui Barradas


-- 
Este e-mail foi analisado pelo software antivírus AVG para verificar a presença de vírus.
www.avg.com



More information about the R-help mailing list