How to get the name data.frame in the list?

How can I get the name of a data frame from a list? Of course, get()the object itself gets, but I want its name to be used in another function. A use case is used here if you prefer to offer a job:

lapply(somelistOfDataframes, function(X) {
    ddply(X, .(idx, bynameofX), summarise, checkSum = sum(value))
})

Each data frame has a column with the same name as the data frame in the list. How can I get this name bynameofX? names(X)will return the whole vector.

EDIT: Here's a reproducible example:

df1 <- data.frame(value = rnorm(100), cat = c(rep(1,50),
    rep(2,50)), idx = rep(letters[1:4],25))
df2 <- data.frame(value = rnorm(100,8), cat2 = c(rep(1,50), 
    rep(2,50)), idx = rep(letters[1:4],25))

mylist <- list(cat = df1, cat2 = df2)
lapply(mylist, head, 5)
+5
source share
3 answers

I would use list names this way:

dat1 = data.frame()
dat2 = data.frame()
l = list(dat1 = dat1, dat2 = dat2)
> str(l)
List of 2
 $ dat1:'data.frame':   0 obs. of  0 variables
 $ dat2:'data.frame':   0 obs. of  0 variables

and then use lapply + ddply, for example:

lapply(names(l), function(x) {
    ddply(l[[x]], c("idx", x), summarise,checkSum = sum(value))
  })

This remains untested without a reproducible answer. But that should help you in the right direction.

EDIT (ran2): .

l <- lapply(names(mylist), function(x) {
ddply(mylist[[x]], c("idx", x), summarise,checkSum = sum(value))
})
names(l) <- names(mylist); l
+5

dplyr

library(dplyr)

catalog = 
  data_frame(
    data = someListOfDataframes,
    cat = names(someListOfDataframes)) %>%
  rowwise %>%
  mutate(
    renamed = 
      data %>%
      rename_(.dots = 
                cat %>%
                as.name %>% 
                list %>%
                setNames("cat")) %>%
      list)

catalog$renamed %>%
  bind_rows(.id = "number") %>%
  group_by(number, idx, cat) %>%
  summarize(checkSum = sum(value))
+1

you can first use the names (list) → list_name, and then use list_name [1], list_name [2], etc., to get the name of each list. (you may also need as.numeric (list_name [x]) if your list names are numbers.

0
source

All Articles