Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

error when using `get` within a dplyr mutate statement in R

I have my R environment with some objects in it.

tmp <- list(1,2,4)
dafa <- data.frame(thing="Yes", 
            value=4)

Lists and Dataframes both come up as list when using:

typeof(get("tmp"))  # list
typeof(get("dafa")) # list

I want to get a dataframe of all the objects in my environment and note whether some of them are dataframes or not using inherits(get(name), "data.frame")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

library(tidyverse)
# get a list of all the objects in the environment and 
# store in a table
data_items <- map_dfr(ls(), \(itm){
    data.frame(name=itm, 
               type=typeof(get(itm)), 
               size=object.size(get(itm)))})

# adjust each row to specify if object is a dataframe
data_items %>% rowwise() %>%
mutate(type = ifelse(inherits(get(name), "data.frame"),
                   "data.frame",
                   type))

However, this complains:

Error in get(name) : first argument has length > 1

Even though it’s rowwise, any idea where I’m going wrong?

>Solution :

data.frame(name = ls(),
           class = sapply(mget(ls()), class))
#      name      class
# dafa dafa data.frame
# tmp   tmp       list

A comparable tidyverse solution would be:

library(purrr)

tibble(name = ls(envir = .GlobalEnv),
       class = map_chr(mget(name, envir = .GlobalEnv), class))
#   name  class     
#   <chr> <chr>     
# 1 dafa  data.frame
# 2 tmp   list    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading