Reputation: 91
At the start of my code i assign the following values
Hierarchy_1 <- "Store_2"
Hierarchy_2 <- "Store"
Hierarchy_3 <- "SKK"
And then i assign them in the following vector, which is my stable columns of my csv. However in order to be a dynamic code there must be a case where Hierarchy_1 will not exist as a column. Is there a function to ignore Hierarchy_1 to avoid deleting it from StableCols vector and later stages of my code?
StableCols<- c(Hierarchy_1,Hierarchy_2,Hierarchy_3,DateName,DepVarName)
Upvotes: 0
Views: 744
Reputation: 3710
You can use the get0
function.
get0
search for an object in R enviroment, return NULL if not found.
Hierarchy_1 <- "Store_2"
Hierarchy_2 <- "Store"
Hierarchy_3 <- "SKK"
StableCols<- c(get0("Hierarchy_1"), Hierarchy_2, Hierarchy_3)
StableCols
# [1] "Store_2" "Store" "SKK"
rm(Hierarchy_1)
StableCols<- c(get0("Hierarchy_1"), Hierarchy_2, Hierarchy_3)
StableCols
# [1] "Store" "SKK"
You can also use the dynGet
function.
StableCols<- c(dynGet("Hierarchy_1", ifnotfound = NULL), Hierarchy_2, Hierarchy_3)
To David:
You are right about dynGet
. I have no idea. Maybe the following info can help.
From ?get
:
dynGet() is somewhat experimental and to be used inside another function. It looks for an object in the callers, i.e., the sys.frame()s of the function. Use with caution.
I tested another function mget
. It also works.
StableCols<- c(unname(unlist(mget("Hierarchy_1", ifnotfound = list(NULL)))),
Hierarchy_2, Hierarchy_3)
Upvotes: 1
Reputation: 1
You can use rm
c(rm(Hierarchy_1), Hierarchy_2, Hierarchy_3, DateName, DepVarName)
or you can use subset
c(subset(StableCols, StableCols!=Hierarchy_1))
Or
StableCols[-1]
will remove element at first index and print rest
Upvotes: 0