如何使用rapply获得子列表中行名称的迭代前缀?
我知道如何使用如何使用rapply获得子列表中行名称的迭代前缀?,r,apply,R,Apply,我知道如何使用rappy向列表的行名称添加字符串 out1 <- rapply(L, function(x) `rownames<-`(x, paste0("lala.", rownames(x))), how="list") out1$a$ct # x1 x2 x3 # lala.a 1 1 1 # lala.b 1 1 1 不起作用,它会屈服 rappy(seq(L)、函数(x)名称(L[[x]])、how=“list”)中的错误: “对象”必
rappy
向列表的行名称添加字符串
out1 <- rapply(L, function(x)
`rownames<-`(x, paste0("lala.", rownames(x))), how="list")
out1$a$ct
# x1 x2 x3
# lala.a 1 1 1
# lala.b 1 1 1
不起作用,它会屈服
rappy(seq(L)、函数(x)名称(L[[x]])、how=“list”)中的错误:
“对象”必须是列表或表达式
也许我需要另一个*应用
,例如mapply
编辑:我想知道这是否可以在*apply
系列的单个基本函数调用中完成
我还尝试了outer
outer(seq(L$a),seq(L$b), Vectorize(function(x, y)
`rownames<-`(L[[x]][[y]], paste0(names(L[[x]])[y], ".", rownames(L[[x]][[y]])))))
数据
L我不确定这是否是您想要的,但是您可以使用Map/mapply来迭代data.frames及其名称,并使用lappy作为二阶列表结构
addString2RowName <- function(df, string) {
row.names(df) <- paste(string, rownames(df), sep = ".")
df
}
lapply(L, function(l) Map(addString2RowName, df = l, string = names(l)))
addString2RowName我喜欢您的解决方案,但是,我想知道这是否可以通过来自*apply
系列的单个函数调用来实现。据我所知,您有一个双嵌套列表结构(data.frames嵌套在列表中嵌套的列表中),并且需要两个循环(或apply系列调用)对于doublelappy
,我们确实可以经常做rappy
,但我无法让它在我的情况下工作;或者我的编辑中的外部
。我真的看不到这样做的方法。您可以使用lappy(名称(L$a),函数(nam){row.names(L$a[[nam]])
x <- 1; y <- 2
`rownames<-`(L[[x]][[y]], paste0(names(L[[x]])[y], ".", rownames(L[[x]][[y]])))
# x1 x2 x3
# tr.a 1 1 1
# tr.b 1 1 1
# $a
# $a$ct
# x1 x2 x3
# ct.a 1 1 1
# ct.b 1 1 1
#
# $a$tr
# x1 x2 x3
# tr.a 1 1 1
# tr.b 1 1 1
#
#
# $b
# $b$ct
# x1 x2 x3
# ct.a 1 1 1
# ct.b 1 1 1
#
# $b$tr
# x1 x2 x3
# tr.a 1 1 1
# tr.b 1 1 1
L <- list(a = list(ct = structure(c(1, 1, 1, 1, 1, 1), .Dim = 2:3, .Dimnames = list(
c("a", "b"), c("x1", "x2", "x3"))), tr = structure(c(1, 1,
1, 1, 1, 1), .Dim = 2:3, .Dimnames = list(c("a", "b"), c("x1",
"x2", "x3")))), b = list(ct = structure(c(1, 1, 1, 1, 1, 1), .Dim = 2:3, .Dimnames = list(
c("a", "b"), c("x1", "x2", "x3"))), tr = structure(c(1, 1,
1, 1, 1, 1), .Dim = 2:3, .Dimnames = list(c("a", "b"), c("x1",
"x2", "x3")))))
addString2RowName <- function(df, string) {
row.names(df) <- paste(string, rownames(df), sep = ".")
df
}
lapply(L, function(l) Map(addString2RowName, df = l, string = names(l)))