Reputation: 13
How can I refer to my dataframe inside a function when building the dataframe name from several strings?
a <- c(1:6)
b <- c("05/12/2012 05:00","05/12/2012 06:00","06/12/2012 05:00",
"06/12/2012 06:00", "07/12/2012 09:00","07/12/2012 07:00")
c <-c("0","0","0","1","1","1")
d <-c("12", "12", "13", "15", "16", "17")
dataframenumber4 <- data.frame(a,b,c,d,stringsAsFactors = FALSE)
I want to select a value from my dataframe.
dataframenumber4[1,4]
[1] 12
But I also want to build a function as I have multiple dataframes I want to select from:
selectvalue <- function(dataframe, number){
paste0(dataframe,number)[1,4]
}
selectvalue("dataframe", "number4")
[1] NA NA NA
I gather this isn't right because R isn't recognizing my little string as an object name. So I tried to fix it:
selectvalue <- function(dataframe, number){
eval(paste0(dataframe,number))[1,4]
}
selectvalue("dataframe", "number4")
Returns "Error in eval(paste0(dataframe,number, quote = FALSE))[1,4]: incorrect number of dimensions"
I've tried multiple things inside my function but I can't get R to recognize that I'm trying to give it my dataframe. How can I fix this?
Upvotes: 1
Views: 1209
Reputation: 20085
You can use get
function to access objects by their name. The name of the data.frame is prepared using paste0(dataframe,number)
and then you can call get
with that name to access dataframe. Hence your function can be written as:
selectvalue <- function(dataframe, number){
get(paste0(dataframe,number))[1,4]
}
selectvalue("dataframenumber",4)
[1] "12"
The above function works per OP's expectation but I should suggest few improvement in that function:
Hence, function can be re-written and called as:
selectvalue <- function(dataframe, rownum, colnum){
get(dataframe)[rownum,colnum]
}
selectvalue(paste0("dataframenumber",4), 1 ,4)
#[1] "12"
selectvalue(paste0("dataframenumber",4), 2 ,2)
#[1] "05/12/2012 06:00"
Upvotes: 1