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")
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?
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
I want to point out that this works on this simplistic example, but often objects have multiple classes, which would cause an error with this code. Using something like is.data.frame
would be helpful here, but the approach is dependent on what you are trying to accomplish.