Calling a data.frame from string - r

I am doing a loop and I need to subset a fixed range of the columns of a data frame. But the loop is exactly to generate the name of the data.frame that I need to extract the columns. I would like to know how can I call a data.frame from a string name. It must be something similar to assign() function, but I am not assigning any value to nothing, I just need to generate the name of a data.frame from a string using paste0() function.

a=5
b="a"
get(b)
Output:
5
How I found this? I did help(assign) and looked under "See also" section.

Related

Referencing recently used objects in R

My question refers to redundant code and a problem that I've been having with a lot of my R-Code.
Consider the following:
list_names<-c("putnam","einstein","newton","kant","hume","locke","leibniz")
combined_df_putnam$fu_time<-combined_df_putnam$age*365.25
combined_df_einstein$fu_time<-combined_einstein$age*365.25
combined_df_newton$fu_time<-combined_newton$age*365.25
...
combined_leibniz$fu_time<-combined_leibniz$age*365.25
I am trying to slim-down my code to do something like this:
list_names<-c("putnam","einstein","newton","kant","hume","locke","leibniz")
paste0("combined_df_",list_names[0:7]) <- data.frame("age"=1)
paste0("combined_df_",list_names[0:7]) <- paste0("combined_df_",list_names[0:7])$age*365.25
When I try to do that, I get "target of assignment expands to non-language object".
Basically, I want to create a list that contains descriptors, use that list to create a list of dataframes/lists and use these shortcuts again to do calculations. Right now, I am copy-pasting these assignments and this has led to various mistakes because I failed to replace the "name" from the previous line in some cases.
Any ideas for a solution to my problem would be greatly appreciated!
The central problem is that you are trying to assign a value (or data.frame) to the result of a function.
In paste0("combined_df_",list_names[0:7]) <- data.frame("age"=1), the left-hand-side returns a character vector:
> paste0("combined_df_",list_names[0:7])
[1] "combined_df_putnam" "combined_df_einstein" "combined_df_newton"
[4] "combined_df_kant" "combined_df_hume" "combined_df_locke"
[7] "combined_df_leibniz"
R will not just interpret these strings as variables that should be created and be referenced to. For that, you should look at the function assign.
Similarily, in the code paste0("combined_df_",list_names[0:7])$age*365.25, the paste0 function does not refer to variables, but simply returns a character vector -- for which the $ operator is not accepted.
There are many ways to solve your problem, but I will recommend that you create a function that performs the necessary operations of each data frame. The function should then return the data frame. You can then re-use the function for all 7 philosophers/scientists.

Dynamically assign elements to object

In R, I am trying to dynamically select columns of a data.frame called DF. If
cutOffYear=2014
and
forecast_years=3
Then this piece of code
paste0("DF$X",cutOffYear+1:forecast_years)
yields:
[1] "DF$X2015" "DF$X2016" "DF$X2017"
Assuming all three columns exist in DF how do I assign the column variables to the characters?
I have tried a lot of combinations of get, assign and paste0 but I am failing.
We can try with [ to select the columns. It is often error prone when using $. If we need to get the output as a data.frame with columns specified in the pasted combination of 'cutOffYear', 'forecast_years', then the below code should work fine
DF[paste0("X", cutOffYear+1:forecast_years)]

Referencing a function parameter in R

I'm working on a function and need to know how to reference the incoming parameters.
For example, in python or lots of other languages, you can reference the input parameters something like this:
sys.argv[1:].
How can I reference the name of a parameter in R?
The specific problem I'm trying to solve is I want to capture the string value of the incoming parameter, so I can paste it as a concentration with a list of column_names I want to iterate through.
Here's the head of the function call, just so you can see the incoming parameter:
function(df_in)
So here's an example of the code I am writing and I want the string value of the dataframe_in, not the object that it references.
col_name <-paste(df_in,varnames[i],sep="$")
if df_in contained "my_df" and the current column_name is my_col, I'm trying to have col_name in the example above set to my_df$my_col.
I was thinking of using the get() function but quite sure how to apply it in this situation.
Thanks
Try something along these lines:
fn1 <- function(df_in){ in_nam <- deparse(substitute(df_in) )
col_names <-paste(in_nam, names(df_in), sep="$")
cat(col_names) }
> dfrm <- data.frame(a=1:10, b=letters[1:10])
> fn1(dfrm)
#dfrm$a dfrm$b
You didn't say what varnames was supposed to be so I'm guessing you want the column names from the object. BTW, don't expect to be able to reference the column values with those character values. They are no longer language objects.

How to use indirect reference to read contents into a data table in R.

How do you use indirect references in R? More specifically, in the following simple read statement, I would like to be able to use a variable name to read inputFile into data table myTable.
myTable <- read.csv(inputFile, sep=",", header=T)
Instead of the above, I want to define
refToMyTable <- "myTable"
Then, how can I use refToMyTable instead of myTable to read inputFile into myTable?
Thanks for the help.
R doesn't really have references like that, but you can use strings to retrieve/create variables of that name.
But first let me say this is generally not a good practice. If you're looking to do this type of thing, it's generally a sign that you're not doing it "the R way.'
Nevertheless
assign(refToMyTable, read.csv(inputFile, sep=",", header=T))
Should to the trick. And the complement to assign is get to retrieve a variable's value using it's name.
I think you mean something like the following:
reftomytable='~/Documents/myfile.csv'
myTable=read.csv(reftomytable)
Perhaps assign as mentioned by MrFlick.
When you want the contents of the object named "myTable" you would use get:
get("myTable")
get(refToMyTable) # since get will evaluate its argument
(It would be better to assign results of multiple such dataframes to a ist object or a Reference Class.)
If you wanted a language-name object you would use as.name:
as.name("myTable")
# myTable .... is printed at the console; note no quotes
str(as.name("myTable"))
#symbol myTable

literal string vs variable string

I want to load a dataset using the data() function. The name of the dataset is obtained from another function.
So I want to do the following:
var1 <- "mydataset"
data(var1)
However, it says that there is not a dataset with var1 as name!
Any suggestion?
data(list=var1)
Since data tries to be helpful and allow for an unquoted name to be specified, you need to be explicit and pass the character vector as the list argument.

Resources