How to get the name of a data.frame within a list?

天涯浪子 提交于 2019-11-30 20:32:11
Paul Hiemstra

I'd use the names of the list in this fashion:

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 like:

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

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

EDIT (ran2): Here's the code using the reproducible example.

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

Here is the dplyr equivalent

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))

you could just firstly use names(list)->list_name and then use list_name[1] , list_name[2] etc. to get each list name. (you may also need as.numeric(list_name[x]) if your list names are numbers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!