0

I'm trying to write a function that will open some .csv files and preform several calculations on specific parts of those dataframes. I'm having trouble passing a column name as a parameter in the function, and I'm not sure why. So something like this (minimal working example, my function is more complex than this):

MyFunction <- function(file, columnname){
    data <- read.table(file,sep=",",header=TRUE);
    mean(data$columnname);
    }

I have a .csv in my desktop called "test.csv", and all it has in it is a column called "numbers" and the numbers 1:10. If I run either of these:

MyFunction("~/Desktop/test.csv",numbers)
MyFunction("~/Desktop/test.csv","numbers")

I get this error:

[1] NA
Warning message:
In mean.default(data$columnname) :
   argument is not numeric or logical: returning NA

However, if I run this:

data <- read.table("~/Desktop/test.csv",sep=",",header=TRUE);
mean(data$numbers);

I get this:

[1] 5.5

... which is what I want.

I'm not sure how my function is different from doing it by hand here. I can use function parameters to find and open the file, but using the function parameter in the data$parameter seems to be causing an error. Why is this? What workaround is there?

2
  • 1
    You could just use bracket indexing instead of indexing by $. For example, get the column number with something like Idx <- match(columnname,names(data)) and then mean(data[,Idx]). Commented Oct 16, 2014 at 21:52
  • I actually ended up using this, although both answers were very helpful! Commented Oct 16, 2014 at 22:27

1 Answer 1

4

Try this:

MyFunction <- function(file, columnname) {
    data <- read.csv(file)
    mean(data[[columnname]])
}

Note:

b <- "a"
DF <- data.frame(a = 1, b = 2)
DF$b
## [1] 2
DF[[b]]
## [1] 1
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome, thank you! Was my problem using read.table or $ or both?
$ is the problem. See clarification just added.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.