Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call an object using a function in R

Tags:

r

I have R objects:

    "debt_30_06_2010" "debt_30_06_2011" "debt_30_06_2012" ...

and need to call them using a function:

    paste0("debt_",date) ## "date" being another object

The problem is that when I assign the call to another object it takes only the name not the content:

    debt_a <- paste0("endeud_", date1)
    > debt_a
    [1] "debt_30_06_2014"

I've tried to use the function "assign" without success:

    assign("debt_a", paste0("debt_", date))
    > debt_a
    [1] "debt_30_06_2014"

I would like to know there is any method to achieve this task.

like image 746
JVALLEJO Avatar asked Nov 28 '25 23:11

JVALLEJO


2 Answers

We could use get to get the value of the object. If there are multiple objects, use mget. For example, here I am assigning 'debt_a' with the value of 'debt_30_06_2010'

 assign('debt_a', get(paste0('debt_', date[1])))
 debt_a
 #[1] 1 2 3 4 5

mget returns a list. So if we are assigning 'debt_a' to multiple objects,

 assign('debt_a', mget(paste0('debt_', date)))
 debt_a
 #$debt_30_06_2010
 #[1] 1 2 3 4 5

 #$debt_30_06_2011
 #[1]  6  7  8  9 10

data

debt_30_06_2010 <- 1:5
debt_30_06_2011 <- 6:10
date <- c('30_06_2010', '30_06_2011')
like image 139
akrun Avatar answered Dec 01 '25 13:12

akrun


I'm not sure if I understood your question correctly, but I suspect that your objects are names of functions, and that you want to construct these names as characters to use the functions. If this is the case, this example might help:

myfun <- function(x){sin(x)**2}
mychar <- paste0("my", "fun")
eval(call(mychar, x = pi / 4))
#[1] 0.5
#> identical(eval(call(mychar, x = pi / 4)), myfun(pi / 4))
#[1] TRUE
like image 20
RHertel Avatar answered Dec 01 '25 12:12

RHertel