问题描述
如何从列表中获取数据框的名称?当然, get()
获取对象本身,但我想让它的名字在另一个函数中使用。这是用例,如果你想建议一个解决方法:
How can I get a data frame's name from a list? Sure, get()
gets the object itself, but I want to have its name for use within another function. Here's the use case, in case you would rather suggest a work around:
lapply(somelistOfDataframes, function(X) {
ddply(X, .(idx, bynameofX), summarise, checkSum = sum(value))
})
每个数据框中都有一列与列表中的数据框同名。我怎样才能得到这个名字 bynameofX
? names(X)
将返回整个向量。
There is a column in each data frame that goes by the same name as the data frame within the list. How can I get this name bynameofX
? names(X)
would return the whole vector.
编辑:这是一个可重复的例子:
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)
推荐答案
我会以这种方式使用列表的名称:
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
然后使用lapply + ddply,如:
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):这是使用可重复示例的代码。
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
这篇关于如何在列表中获取data.frame的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!