简体   繁体   English

用户定义函数中的data $ column返回null

[英]data$column returning null in a user-defined function

I'm new at R (and stackoverflow , too), so please forgive any possible stupidity! 我是R(和stackoverflow)的新手,所以请原谅任何可能的愚蠢!

I wrote a function 我写了一个函数

     getvariance <-function(data, column)

that returns the variance of values in column in data 返回data column中值的方差

In the function I wrote 在我写的函数中

    mydata = read.csv(data)
    for i=1:datasize {
      x=(mydata$column)[i]
      //compute variance of x
    }

When I call 当我打电话

     getvariance("randomnumbers.csv", X1)

x is returned as a column of null values. x作为空值列返回。

However, when I simply write 但是,当我简单地写

     x=(mydata$X1[i])

it prints the full column with numerical values. 它用数值打印整列。

Can anyone help me understand why mydata$column[i] doesn't work when column's a parameter of a function? 谁能帮我理解为什么当列是函数的参数时mydata$column[i]不起作用?

Thanks in advance. 提前致谢。

You are trying to access data$column instead of data$X1 . 您正在尝试访问data$column而不是data$X1

data <- data.frame(X1=1:3)
data$X1
## [1] 1 2 3
data$column
## NULL

Instead try to actually access the column with the name X1 as follows: 而是尝试实际访问名称为X1的列,如下所示:

fct <- function(data, column){
  data[,column]
}
fct(data, "X1")
## [1] 1 2 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM