使用函数内的$索引数据框? [英] Indexing a dataframe with $ inside a function?

查看:99
本文介绍了使用函数内的$索引数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多R教科书鼓励使用$从data.frames ^中检索变量(列)。但是,我发现这在函数内部不起作用,我无法弄清楚原因。

Many R textbooks encourage the use of $ to retrieve variables (columns) from data.frames^. However, I found that this does not work inside a function, and I can't figure out why.

data(BOD)
print(BOD)

# These work. 
BOD$'demand'
BOD[ ,'demand']

# This works.
myFunc1 <- function(x, y){
  z <- x[ , y]
  return(z)
}
out <- myFunc(BOD, 'demand')

# This doesn't work.
myFunc2 <- function(x, y){
  z <- x$y
  return(z)
}
out <- myFunc2(BOD, 'demand')

我注意到在R语言定义中它说:

I notice that in the R Language Definition it says:


使用$的表单适用于列表和pairlists等递归对象。它只允许使用文字>字符串或符号作为索引。也就是说,索引是不可计算的:对于需要评估表达式以查找索引的情况,请使用x [[expr]]。当$应用于>非递归对象时,结果总是为NULL:从R 2.6.0开始,这是一个错误。

The form using $ applies to recursive objects such as lists and pairlists. It allows only a literal >character string or a symbol as the index. That is, the index is not computable: for cases where >you need to evaluate an expression to find the index, use x[[expr]]. When $ is applied to a >non-recursive object the result used to be always NULL: as from R 2.6.0 this is an error.

myFunc2上面是一个例子,其中$没有提供文字字符串吗?

Is myFunc2 above an example where $ is not being supplied a literal character string?

^ Zuur 2009'R'61的初学者指南

^ Zuur 2009 'Beginner's Guide to R' p 61

^ Spector 2008'数据操作与R'p 26,64,69

^ Spector 2008 'Data Manipulation with R' p 26, 64, 69

推荐答案

你也可以使用[[而不是$

You can use also [[ instead of $

myFunc2 <- function(x, y){
+     z <- x[[y]]
+     return(z)
+ }
> myFunc2(BOD, 'demand')
[1]  8.3 10.3 19.0 16.0 15.6 19.8

这篇关于使用函数内的$索引数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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