英文:
extracting the names of a lists on which we are applying a function in lapply
问题
我想提取在lapply()函数内应用函数的列表元素的名称。编辑:也许这不太清楚,为了澄清一下,必须在lapply()中完成。
以下是一个可重现的示例,以便澄清:
A <- c("z", "y", "x", "v")
B <- c("q", "j", "k", "r")
C <- c("n", "e", "d", "f")
myList <- list(A = A, B = B, C = C)
names_list <- lapply(myList, function(x) {
???(x)
})
output: "A" "B" "C"
我不确定如何完成这个任务,我在网上找不到任何信息。我最接近期望输出的方法是使用envnames包中的get_obj_name函数,但它给了我以下结果:
$A
[1] "x"
$B
[1] "x"
$C
[1] "x"
谢谢你的帮助。
英文:
I want to extract the names of the elements of a list on which I am applying a function within the lapply(). EDIT: perhaps this was not clear so just to clarify it has to be done in lapply().
Here is a reproducible example to clarify.
A <- c("z", "y", "x", "v")
B <- c("q", "j", "k", "r")
C <- c("n", "e", "d", "f")
myList <- list(A = A,B = B, C = C)
names_list <- lapply(myList, function(x) {
???(x)
})
output: "A" "B" "C"
I am not sure how this could be done, and I cannot find any information online. The closest I have come to the desired output is by using
get_obj_name from the envnames package but it gives me
$A
[1] "x"
$B
[1] "x"
$C
[1] "x"
Thank you for your help.
答案1
得分: 2
使用lapply处理列表的名称而不是列表本身。 使用tibble包中的lst形成列表,因为它会自动添加名称到列表中。
library(tibble)
L <- lst(A, B, C) # lst创建列表并添加名称
res <- lapply(names(L), function(nm) {
x <- L[[nm]]
print(nm)
print(x)
nm
})
另一种方法是同时传递名称和值:
res2 <- Map(function(nm, x) {
print(nm)
print(x)
nm
}, names(L), L)
英文:
lapply over the list names rather than over the list itself. Form the list
using lst from the tibble package as that will automatically add names to the
list.
library(tibble)
L <- lst(A, B, C) # lst creates list and adds names
res <- lapply(names(L), function(nm) {
x <- L[[nm]]
print(nm)
print(x)
nm
})
Another approach is to pass both the names and the values:
res2 <- Map(function(nm, x) {
print(nm)
print(x)
nm
}, names(L), L)
答案2
得分: 1
你的列表没有名称,你可以这样编程,然后就不需要lapply
了。
A <- c("z", "y", "x", "v")
B <- c("q", "j", "k", "r")
C <- c("n", "e", "d", "f")
myList <- list(A=A, B=B, C=C)
names_list <- lapply(names(myList), function(x) {print(x)})
names_list
英文:
Your lists do not have names with how you programmed it. You'd have to code it like this and then you would not need the lapply
A <- c("z", "y", "x", "v")
B <- c("q", "j", "k", "r")
C <- c("n", "e", "d", "f")
myList <- list(A=A, B=B, C=C)
names_list <- lapply(names(myList), function(x) {print(x)})
names_list
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论