Remove all objects from environment except those matching a given pattern - r

I'm trying to remove all objects from my RStudio environment where the object names are NOT equal to a pattern.
rm(list=ls(pattern!="may19"))
However this gives me an error
Error in as.environment(pos) : no item called "pattern != "may19""
on the search list
Is there another way to approach this?
Thanks in advance

We could use one of the following(other variants might exist, you can add all=TRUE or all.names=TRUE) for completeness:
rm(list=setdiff(ls(),"may19"))
rm(list=ls(pattern = "[^may19]"))

Related

Avoid partial matching of list names? [duplicate]

I thought that R did not do partial matching on named lists, so I'm confused by the example below. I tried reading the Argument matching document but I'm still not sure of what's going on. Any help understanding this example would be appreciated.
ll <- list("dir_session" = "some_directory")
print(ll$dir_session) # prints contents of ll$dir_session as expected
print(ll$dir) # prints contents of ll$dir_session, but I expected to print NULL
print(ll[["dir"]]) # prints NULL as expected
Not sure if it makes a difference but I'm using R version 3.3.3 (2017-03-06).
I'm afraid the answer is you thought wrong. It has less to do with the class of object (a named list) and more to do with the "$" operator which does partial matching. See the ?Extract help page. This is different than argument matching when calling a function.

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.

Renaming Multiple Columns in R using Rename

I have already checked the forum for the solution but could not find the solution, hence, posting the problem here.
I am trying to change a name of a column using Rename, although the command is executed without any error but the names of the columns does not change.
I use this coderename(red,parts = category) Thanks
You need to pass a named vector as the second argument, and the names need to be quoted. Also, don't forget that you need to overwrite red with the result.
red <- reshape::rename(red, c(parts = "category"))
If you want to change multiple columns, add the items to the named vector you supply to the second argument.

Remove all objects from R environment whose names DO NOT contain a specific string

I'd like to remove all objects from my RStudio environment where the object names DO NOT contain a given string.
rm(list=ls(pattern!="may19"))
Yet this gives me an error message
Error in as.environment(pos) : no item called "pattern != "may19"" on
the search list
Is there another way I can approach this? Thanks
You can do:
rm(list= names(Filter(function(x) !any(names(x) == "may19"),
mget(ls(),envir = .GlobalEnv))))
Or simply(as suggested by #nicola):
rm(list=grep("may19",ls(),value=TRUE,invert=TRUE))

save get'd variable (after assign)

Why can't R find this variable?
assign(paste0('my', '_var'), 2)
get(paste0('my', '_var')) ## isn't this returning an object?
save(get(paste0('my', '_var')), file = paste0('my', '_var.RDATA'))
This throws the error:
Error in save(paste0("my", "_var"), file = paste0("my", "_var.RDATA")) :
object ‘paste0("my", "_var")’ not found
From the help page, the save() function expects "the names of the objects to be saved (as symbols or character strings)." Those values are not evaulated, ie you can't put in functions that will eventually return strings or raw values themselves. Use the list= parameter if you want to call a function to return a string the the name of a variable.
save(list=paste0('my', '_var'), file = paste0('my', '_var.RDATA'))
Though using get/assign is often not a good practice in R. They are usually better ways so you might want to rethink your general approach.
And finally, if you are saving a single object, you might want to consider saveRDS() instead. Often that's the behavior people are expecting when they use the save() function.
The documentation for save says that ... should be
the names of the objects to be saved (as symbols or character strings).
And indeed if you type save into the console you can see that the source has the line
names <- as.character(substitute(list(...)))[-1L]
where substitute captures its argument and doesn't evaluate it. So as the error suggests, it is looking for an object with the name paste0('my', '_var'), not evaluating the expressions supplied.

Resources