Reputation: 237
I have a R code that looks something like this:
StatFunction <- function(CSVImport, AnimalID_i,Treatment_i){
#Data Input from a CSV file (example below)
Data <- read.csv(CSVImport)
All goes well so far, as the data is read off the csv file. I am calling the function like this
StatFunction (path/to/file/, "Animal", "Treatment")
Note that the input arguments are strings representing the column name of the CSV. Now, I try to sort out the data frame like this:
#Trying to sort out the input
Data <- within(Data, {
FinalID <- (factor(as.character(FinalID_i)))
AnimalID <- (factor(as.character(AnimalID_i)))
This doesn't work with the argument of the StatFunction. It gives me this
[1] "---Final ID---"
[1] Treatment
Levels: Treatment
[1] "---Animal ID---"
[1] Animal
Levels: Animal
When, Substituting the arguments directly into the code, like this
FinalID <- (factor(Treatment))
AnimalID <- (factor(Animal))
It gives me the expected result.
[1] "---Final ID---"
[1] 0 0 1 1 1
Levels: 0 1
[1] "---Animal ID---"
[1] 722 723 724 727 728
Levels: 722 723 724 727 728
So my question is how to make this work when passing arguments and not burning the names in the code?
Upvotes: 0
Views: 800
Reputation: 99331
Why not go back a step and add the fact that you want factor columns via their names by adding a colClasses
argument that is passed to read.csv()
. Or you can just add , ...)
and do the same thing. The ...
can be sent to the read.csv()
argument list.
statFunction <- function(file, colClasses = character(), ...) {
read.csv(file, colClasses = colClasses, ...)
}
And call statFunction()
like this
statFunction(
file,
colClasses = c(Animal = "factor", Treatment = "factor")
)
Upvotes: 0
Reputation: 206197
You can't just swap character and symbol values. If you want to extract data with a character value, then use
Data$FinalID <- factor(as.character(Data[[FinalID_i]]))
Data$AnimalID <- factor(as.character(Data[[AnimalID_i]]))
Upvotes: 1