Concatenating string names of variables matlabfile in R

烈酒焚心 提交于 2019-12-12 04:36:25

问题


I have matlab files with an integer in each name of my variables inside (except the first one). I want to loop to concatenate the name of the integers. There is my code:

library('R.matlab')
mat <- readMat('SeriesContPJM.mat')
#str(mat)
#typeof(mat)
                                        #mat[[1]]
write.csv(mat$vol.PJM$data[[4]][[1]], "PJM.csv")
i = 2
while (i < 7)
{
    write.csv(get(paste("mat$vol.PJM", as.character(i), "$data[[4]][[1]]", sep = "")), paste(paste("PJM", as.character(i), sep="_"), "csv", sep ="."))
    i = i + 1
}

I have write.csv(mat$vol.PJM$data[[4]][[1]], "PJM.csv") which gives me the good ouput. I would like the same for the other variable names in the loop but I get the following ouput:

+ Error in get(paste("mat$vol.PJM", as.character(i), "$data[[4]][[1]]",  (from importpjm.R#10) : 
  objet 'mat$vol.PJM2$data[[4]][[1]]' introuvable

"introuvable" means "not found" in French.


回答1:


Here you're mixing where you need to use get and where you need to use eval(parse()).

You can use get with a string variable game, e.g., get("mtcars"), but [ is a function that needs to be evaluated.

  • get("mtcars[2, 2]") won't work because you don't have a variable named "mtcars[2, 2]", you have a variable named "mtcars" and a function named "[" that can take arguments 2, 2.

  • eval(parse(text = "mtcars[2, 2]")) will work because it doesn't just look for a variable, it actually evaluates the text string as if you typed it into the command line.

So, you could rewrite your loop, replacing the get(...) with eval(parse(text = ...)) and it would probably work, assuming the strings you've pasted together have the right syntax. But this can be difficult to read and debug. In 6 months, if you look back at this code and need to understand it or modify it, it will be confusing.

Another way to do it would be to use [[ with strings to extract sublists. Rather than mess with eval(parse()) I would do this:

vols = paste0("vol.PJM", 2:7)
for (vol in vols) {
    write.csv(mat[[vol]][["data"]][[4]][[1]],
              paste0(vol, ".csv"))
}

I think it's more readable, and it's easy to debug the vols vector beforehand to make sure all your names are correct. Similarly, if you want to loop over all elements, you could initialize the vols as something like names(mat), or use some sort of regex criteria to extract the appropriate sublists from names(mat).



来源:https://stackoverflow.com/questions/41708969/concatenating-string-names-of-variables-matlabfile-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!