问题
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