[R] simple problem with unquoting argument

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Wed Jul 3 10:24:21 CEST 2024


Às 09:13 de 03/07/2024, Troels Ring escreveu:
> Hi  friends - I'm in problems finding out how to unquote - I have a 
> series of vectors named adds1....adds11 and need to e.g. find the sum of 
> each of them
> 
> So I try
> 
> SS <- c()
> 
> for (i in 1:11) {
> 
> e <- paste("adds",i,sep="")
> 
> SS[i]  <- sum(xx(e)) }
> 
> Now e looks right - but I have been unable to find out how to get the 
> string e converted to the proper argument for sum()  - i.e. what  is 
> function xx?
> 
> All best wishes
> Troels Ring, Aalborg, Denmark
> 
> ______________________________________________
> 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,

Function xx is ?get or mget (same help page).
You can get the vectors adds all in one instruction with mget or one at 
a time with get.


adds1 <- 1:10
adds2 <- 2:10
adds3 <- 3:10
adds4 <- 4:10
adds5 <- 5:10

# create SS with the required length beforehand
SS <- numeric(5L)
for (i in 1:5) {
   e <- paste("adds",i,sep="")
   SS[i]  <- sum(get(e))
}
SS
#> [1] 55 54 52 49 45


Or all in one instruction with the assistance of ?ls.



# ls(pattern = "^adds") |> mget() |> lapply(sum)
ls(pattern = "^adds") |> mget() |> sapply(sum)
#> adds1 adds2 adds3 adds4 adds5
#>    55    54    52    49    45


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