评估存储为字符串值的dataframe $ column表达式 [英] Evaluate dataframe$column expression stored as a string value

查看:78
本文介绍了评估存储为字符串值的dataframe $ column表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以对下面形式的字符串求值,使其等同于相同的文字表达式?

Can a string of the form below be evaluated so that it is equivalent to the same "literal" expression?

示例数据和代码:

df.name = data.frame(col1 = 1:5, col2 = LETTERS[seq(1:5)], col3 = letters[seq(1:5)], stringsAsFactors = FALSE)
col.name = "col2"
row.num = "4"

var1 = str_c("df.name$", col.name,"[",row.num,"]")

> var1
[1] "df.name$col2[4]"

原义作品按预期

> df.name$col2[4]
[1] D

get()不等效:

get(var1)
## Error in get(var1) : object 'df.name$col2[4]' not found

此表单 get()的作品,但不能解决问题

This form of get() "works" but does not solve the problem

get("df.name")$col2[4]
[1] D

我尝试过的其他帖子 eval(parse()) eval(parse(text()))成功。

Per other posts I've tried eval(parse()) and eval(parse(text())) without success.

我正在尝试创建一个函数,该函数将使用<$ c搜索(子集) df.name $ c> col.name 传递给函数。我想避免为每个列名编写一个单独的函数,尽管那样可以工作,因为我可以将 df.name $ col2 [row.num] 编码为文字。

I'm trying to create a function that will search (subset) df.name using the col.name passed to the function. I want to avoid writing a separate function for each column name, though that will work since I can code df.name$col2[row.num] as a "literal".

示例代码应已将row.num显示为数字/整数类型,即 row.num = 4

The example code should have shown the row.num as type numeric / integer, i.e., row.num = 4

推荐答案


I正在尝试创建一个函数,该函数将使用传递给该函数的col.name搜索(子集)df.name。

I'm trying to create a function that will search (subset) df.name using the col.name passed to the function.

设置数据:

df.name = data.frame(col1 = 1:5, col2 = LETTERS[1:5], ## seq() is unnecessary
                     col3 = letters[1:5], 
                     stringsAsFactors = FALSE)
col.name = "col2"
row.num = "4"

解决最终问题(按列名称为数据框编制索引),而不是近端问题(找出如何使用 get() / eval( )等)问题:正如@RichardScriven指出的那样,

Solving your ultimate (index the data frame by column name) rather than your proximal (figure out how to use get()/eval() etc.) question: as @RichardScriven points out,

f <- function(col.name,row.num,data=df.name)
   return(data[[col.name]][as.numeric(row.num)])
}

应该可以。如果将行号指定为数字而不是字符,则可能更惯用……

should work. It would probably be more idiomatic if you specified the row number as numeric rather than character, if possible ...

这篇关于评估存储为字符串值的dataframe $ column表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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