literal string vs variable string - r

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.

Related

How do I use get() in R to access a variable with another variable?

I have a loop which is running over a vector containing names of a few tens of dataframes that are in my environment. On each iteration, I want to access the dataframe using the name, and access a specific column within it. As I understand it, the best way to access a variable with a string is using get().
But when I try and do this (with name being a variable containing the string "first.name"):
get(column.name, name)
I get the error:
Error in as.environment(pos) : no item called "first.name" on the search list
It does work if I try to run:
get(column.name, first.name)
So, assuming that get() is the right function for this, what am I doing wrong?
Reproduceable example:
my.df <- as.data.frame(x = seq(1:10), y = rnorm(10))
name <- "my.df"
get("x",name)
We may need to use
get(name)[[column.name]]

R seems to ignore part of variable name after underscore

I encountered a strange problem with R. I have a dataframe with several variables. I add a variable to this dataframe that contains an underscore, for example:
allres$tmp_weighted <- allres$day * allres$area
Before I do this, R tells me that the variable allres$tmp does not exist (which is right). However, after I add allres$tmp_weighted to the dataframe and call allres$tmp, I get the data for allres$tmp_weighted. It seems as if the part after the underscore does not matter at all for R. I tried it with several other variables / names and it always works that way
I don't think this should work like this? Am I overlooking something here? Below I pasted some code together with output from the Console.
# first check whether variable exists
allres_sw$Ndpsw
> NULL
#define new variable with underscore in variable name
allres_sw$Ndpsw_weighted <- allres_sw$Ndepswcrit * allres_sw$Area
#check again whether variable exists
allres_sw$Ndpsw
> [1] 17.96480 217.50240 44.84415 42.14560 0.00000 43.14444 53.98650 9.81939 0.00000 110.67720
# this is the output that I would expect from "Ndpsw_weighted" - and indeed do get
allres_sw$Ndpsw_weighted
> [1] 17.96480 217.50240 44.84415 42.14560 0.00000 43.14444 53.98650 9.81939 0.00000 110.67720
Have a look at ?`[` or ?`$` in your R console. If you look at the name argument of the extract functions it states that names are partially matched when using the $ operator (as opposed to the `[[` operator, which uses exact matches based on the exact = TRUE argument).
From ?`$`
A literal character string or a name (possibly backtick quoted). For extraction, this is normally (see under ‘Environments’) partially matched to the names of the object.
Just to expand somewhat on Wil's answer... From help('$'):
x$name
name
A literal character string or a name (possibly backtick
quoted). For extraction, this is normally (see under
‘Environments’) partially matched to the names
of the object.
x$name is equivalent to
x[["name", exact = FALSE]]. Also, the partial matching
behavior of [[ can be controlled using the exact argument.
exact
Controls possible partial matching of [[ when
extracting by a character vector (for most objects, but see under
‘Environments’). The default is no partial matching. Value
NA allows partial matching but issues a warning when it
occurs. Value FALSE allows partial matching without any
warning.
The key phrase here is partial match (see pmatch). You'll understand now that the underscore is nothing special - you can abbreviate allres_sw$Ndpsw_weighted to allres_sw$Ndp, provided no name is more similar than allres_sw$Ndepswcrit.

Calling a data.frame from string

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.

R | replace environment name by a variable

a newbie question: I want to write a universal function which saves variables in a new environment. The name of the environment I want to give as argument in to the function.
#create environment
my.env <- new.env()
#variable to store the name of the environment
env_n<-"my.env"
# now safe a variable a with value 1 to my.env
my.env$a=1 #working
But I want to have a universal solution which works for many cases, there for I want to use the variable which stores the name of the environment. Something like:
#Things I tried
env_n$a=1 #not working
assign(a, 1, envir=env_n)
Can you help me? Thanks a lot!
The first parameter to assign() should be a character value, not a symbol. And the envir= parameter should be a proper environment, not a character value. If you want to get the value of a variable given a character value of the variable name, you use get(). This should work
assign("a", 1, envir=get(env_n))
But this is a very unusual operation for a "newbie" to be using. I would take a step back and look and what you are trying to do and see if there isn't a more "R-like" way to do things.

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.

Resources