eval parse save string to variable

纵饮孤独 提交于 2021-02-08 11:50:23

问题


I have table with variable names and observation for this variable. Some of these observations should be saved to variable as text.

I can't find any other way to deal with except the following, which is not working:

x    <- data.frame( c("Name1","Name2","Name3"),
                    c("Result1",2,"Result3") )
txt  <- paste(x[,1], "<-", x[,2], sep="")
eval(parse(text=txt))

Error in eval(parse(text = txt)) : object 'Result1' not found

I need to get the result where Name1 = "Result1"


回答1:


Ideally you should not be creating such multiple objects in the global environment. It is difficult to manage them. However, for some reason if you have to do it here is one way :

data <- type.convert(setNames(as.list(x[[2]]), x[[1]]), as.is = TRUE)
list2env(data, .GlobalEnv)

We create a named list where value is from 2nd column and name is from 1st column of x. We then use type.convert to convert the data into their respective types. Finally use list2env to have Name1, Name2, Name3 as variables in your global environment.




回答2:


Try this. The issue is that objects like Result1 or Result2 can not be found:

#Data
x    <- data.frame( c("Name1","Name2","Name3"),
                    c("Result1",2,"Result3") )
#Text
txt  <- paste(x[,1], "<-", '\"',x[,2],'\"', sep="")
#Evaluation    
eval(parse(text=txt))

If numeric needed to be kept, play with data types:

#Data
x    <- data.frame( c("Name1","Name2","Name3"),
                    c("Result1",2,"Result3"),stringsAsFactors = F )
#Text
txt  <- ifelse(!is.na(as.numeric(x[,2])),paste(x[,1], "<-", as.numeric(x[,2]), sep=""),
               paste(x[,1], "<-", '\"',x[,2],'\"', sep=""))
#Eval
eval(parse(text=txt))



回答3:


I guess you might need to adapt your data.frame x a bit like below

x <- data.frame(
  c("Name1", "Name2", "Name3"),
  c("Result1", 2, "Result3")
)
x[,2] <- type.convert(x[,2],as.is = TRUE)
x[,2] <- ifelse(is.na(as.numeric(x[,2])),paste0("\'",x[,2],"\'"),x[,2])

where single quotes '' are needed to wrap Result1 and Result2

Then you will see

> Name1
[1] "Result1"

> Name2
[1] 2

> Name3
[1] "Result3"

> class(Name1)
[1] "character"

> class(Name2)
[1] "numeric"

> class(Name3)
[1] "character"


来源:https://stackoverflow.com/questions/64078413/eval-parse-save-string-to-variable

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