loop on a selection of vectors

Hi,
I'am making a script to automate the data extraction. In general, the number of devices may vary, but in my example here, i've 3 devices.
They are composed as follows (vector):
general : gerat+i <-(namegerat i, othername gerat i, ppb, sprache gerat i )

in real :
gerat1<-("DUT$1","16e","1","d")
gerat2<-("DUT$7","22e","0.01","d")
gerat3<-("DUT$8","32","1","f")

I don't always have 3 devices, so i would like to make a loopfor to extracts the 3rd value of each vector ... But i can't find the ways to name "gerat +i". Please can you help me??

You can use eval(parse(text=<string>)), where <string> is the command you want to execute.

For example (note I have added 'c' to get the syntax right):

gerat1 <- c("DUT$1","16e","1","d")
gerat2 <- c("DUT$7","22e","0.01","d")
gerat3 <- c("DUT$8","32","1","f")

nGerat <- 3   # however many you have
thirds <- rep("", nGerat)
for (ii in 1:nGerat) {
   cmd <- sprintf("gerat%d[3]", ii)
   thirds[ii] <- eval(parse(text = cmd))
}

but the advice in fortunes(106) is valid:

If the answer is parse() you should usually rethink the question.
-- Thomas Lumley
R-help (February 2005)

If you can store the original gerat values, however sourced, in a more appropriate manner - e.g. a list - then it will probably be much easier to get what you really need. If instead you can do something like:

gerat <- list()
gerat[[1]] <- c("DUT$1","16e","1","d")
gerat[[2]] <- c("DUT$7","22e","0.01","d")
gerat[[3]] <- c("DUT$8","32","1","f") 

thirds <- sapply(gerat, function(g) g[3])
>thirds
[1] "1"    "0.01" "1" 
thirds2 <- rep("", length(gerat))
for (ii in seq_along(gerat)) {
   thirds2[ii] <- gerat[[ii]][3]
}
>thirds2
[1] "1"    "0.01" "1" 

is a much more robust solution.

1 Like

Thanks a lot ! It works well thank you!

How about these 4 alternatives?

gerat <- list()
gerat[[1]] <- c("DUT$1","16e","1","d")
gerat[[2]] <- c("DUT$7","22e","0.01","d")
gerat[[3]] <- c("DUT$8","32","1","f") 

alt1 <- sapply( gerat, '[[', 3 )  # In vector form
alt1
#> [1] "1"    "0.01" "1"
alt2 <- sapply( gerat, '[[', 3, simplify = TRUE )  # same as the first 
alt2
#> [1] "1"    "0.01" "1"
alt3 <- unlist( sapply( gerat, '[[', 3, simplify = FALSE ) ) # simplify is TRUE by default
alt3
#> [1] "1"    "0.01" "1"
alt4 <- unlist( lapply( gerat, '[[', 3 ) ) # Same as sapply with simplify = FALSE
alt4
#> [1] "1"    "0.01" "1"

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.