Вопрос

I'm new at R (and stackoverflow , too), so please forgive any possible stupidity!

I wrote a function

     getvariance <-function(data, column)

that returns the variance of values in column in data

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.

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?

Thanks in advance.

Это было полезно?

Решение

You are trying to access data$column instead of 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:

fct <- function(data, column){
  data[,column]
}
fct(data, "X1")
## [1] 1 2 3
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top