如何使用R中的字符串引用数据帧元素? [英] How do I refer to a data frame element with strings in R?

查看:209
本文介绍了如何使用R中的字符串引用数据帧元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  n < -  1 
sn< - n
get(sn)

这将工作。但是,以下内容将不起作用:

  n < -  as.data.frame(matrix(1,2,2 )
sn< - n $ V1
get(sn)

如何使这项工作?

  eval(parse(text = sn))

的作品。谢谢。

我这样做是因为数据帧中有1000个变量,我需要一个从一个函数传递的变量来告诉我需要的1000个变量中的哪个变量

解决方案

你几乎肯定只想传递数据框内列的名称,然后使用 [[ -indexing]以检索您想要的矢量:

  n < -  as.data.frame(matrix(1,2,2))
sn< - V1
n [[sn]]
## [1] 1 1


n <- 1
sn <- "n"
get (sn)

This will work. However, the following won't work:

n <- as.data.frame(matrix(1,2,2))
sn <- "n$V1"
get (sn)

How should I make this work?

eval(parse(text=sn))

works. Thanks.

I am doing that because there are 1000 variables in the dataframe and I need a variable passed from a function to tell which variable out of the 1000 variables that I need to work further on.

解决方案

You almost certainly want to pass just the name of the column within the data frame, then use [[-indexing to retrieve the vector you want:

n <- as.data.frame(matrix(1,2,2))
sn <- "V1"
n[[sn]]
## [1] 1 1

这篇关于如何使用R中的字符串引用数据帧元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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