我知道如何使用rapply
将字符串添加到列表的行名。
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
如果我想根据子列表的名称迭代字符串,怎么办?
在lapply
情况下,我将使用lapply(seq_along(L)
遍历序列,但是不确定rapply
是否适用。例如
out2 <- rapply(seq_along(L), function(x) names(L)[x], how="list")
无效,并且产生
Error in rapply(seq(L), function(x) names(L[[x]]), how = "list") :
'object' must be a list or expression
也许我需要另一个*apply
,例如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]])))))
失败了:
Error in dim(robj) <- c(dX, dY) :
dims [product 4] do not match the length of object [24]
同时
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")))))
答案 0 :(得分:1)
我不确定这是否是您想要的,但是您可以使用Map / mapply遍历data.frames及其名称,并将lapply用于您的二阶列表结构。
addString2RowName <- function(df, string) {
row.names(df) <- paste(string, rownames(df), sep = ".")
df
}
lapply(L, function(l) Map(addString2RowName, df = l, string = names(l)))