评估解析将字符串保存到变量 [英] eval parse save string to variable

查看:71
本文介绍了评估解析将字符串保存到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,其中包含变量名称和对该变量的观察.其中一些观察结果应另存为文本变量.

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))

eval(parse(text = txt))中的错误:找不到对象'Result1'

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

我需要得到Name1 ="Result1"的结果

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

推荐答案

理想情况下,您不应在全局环境中创建此类多个对象.很难管理它们.但是,出于某种原因,如果您必须在此处执行操作,则这是一种方法:

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)

我们创建一个命名列表,其中值来自 x 的第二列,名称来自第一列.然后,我们使用 type.convert 将数据转换为各自的类型.最后,使用 list2env Name1 Name2 Name3 作为全局环境中的变量.

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.

这篇关于评估解析将字符串保存到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆