在列表中,我想找到哪个元素具有某个特定长度 并且只打印哪个元素是这个并用它替换它的值 平均值:
A <- c(10)
B <- c(20, 30)
C <- c(40)
D <- c(50)
ll <- list(A, B, C, D)
names(ll) <- c("A", "B", "C", "D")
Foo <- function(x){
if (length(x)>1) {
print() # What should i enter here in order to receive the name of B
x <- mean(x)
} else {
x <- x
}
}
ll_new <- lapply(ll, Foo)
我应该在打印功能中输入什么才能收到名称B?
答案 0 :(得分:2)
这将给你想要的东西:
Foo <- function(x){
if (length(ll[[x]])>1) {
print(x)
x <- mean(ll[[x]])
} else {
x <- ll[[x]]
}
}
ll_new <- lapply(setNames(names(ll), names(ll)), Foo)
# [1] "B"
ll_new
# $A
# [1] 10
#
# $B
# [1] 25
#
# $C
# [1] 40
#
# $D
# [1] 50