我希望将此列表子集化(名称的第一部分是子集化所需的产品名称):
C <- list("110.2000"=matrix(sample(1:10,9), nrow=3, ncol=3),
"111.2000"=matrix(sample(1:10,9), nrow=3, ncol=3),
"112.2000"=matrix(sample(1:10,9), nrow=3, ncol=3),
"111.2001"=matrix(sample(1:10,9), nrow=3, ncol=3),
"112.2001"=matrix(sample(1:10,9), nrow=3, ncol=3),
"111.2002"=matrix(sample(1:10,9), nrow=3, ncol=3),
"113.2000"=matrix(sample(1:10,9), nrow=3, ncol=3))
names <- list(c("A", "B", "C"), c("A", "B", "C"))
C <- lapply(C, function (x) {dimnames(x) <- names; return(x)})
基于此名称(仅限产品名称):
A <- list("111"=matrix(sample(1:10,9), nrow=3, ncol=3),
"112"=matrix(sample(1:10,9), nrow=3, ncol=3))
names <- list(c("A", "B", "C"), c("A", "B", "C"))
A <- lapply(A, function (x) {dimnames(x) <- names; return(x)})
因此,我需要暂时将C的元素名称(例如111.2000分成111)分开。在使用正则表达式的单一提取中,我理解使用此:
foo <- "111.2000"
gsub("\\..*.","",foo)
但是如何在我的列表中应用或lapply到子集?我试过这个,但实际上并不是一个子集,它不起作用:
lapply(function(x) C, gsub("\\..*.","",names(C)))
我的预期输出是:
$`111.2000`
A B C
A 1 8 6
B 3 4 9
C 7 10 5
$`112.2000`
A B C
A 6 4 9
B 1 10 7
C 5 8 3
$`111.2001`
A B C
A 8 10 7
B 3 9 6
C 2 1 4
$`112.2001`
A B C
A 3 6 7
B 1 2 4
C 8 9 10
想法?谢谢
答案 0 :(得分:1)
如果我没有弄错的话,就不需要申请家庭。
# get names
A.nam <- names(A)
C.nam <- names(C)
# get the first part of the names
C.nam.p1 <- gsub("\\..*.","", C.nam)
# decide what parts to choose
C.choose <- C.nam.p1 %in% A.nam
# choose the parts
C.chosen <- C[C.choose]
C.chosen
# $`111.2000`
# A B C
# A 8 3 4
# B 5 6 2
# C 1 9 7
#
# $`112.2000`
# A B C
# A 8 2 5
# B 10 7 6
# C 3 4 9
#
# $`111.2001`
# A B C
# A 10 5 1
# B 8 4 6
# C 7 3 9
#
# $`112.2001`
# A B C
# A 10 7 4
# B 3 9 8
# C 5 6 2
#
# $`111.2002`
# A B C
# A 8 4 1
# B 3 9 6
# C 7 2 10
这会给你你想要的吗?
答案 1 :(得分:0)
如果您先将数据转换为普通表单,这可能会更容易。
library(dplyr)
library(tidyr)
C_fix =
C %>%
lapply(. %>% as.data.frame %>% add_rownames) %>%
bind_rows(.id = "product_year") %>%
separate(product_year,
c("product", "year"))
A_fix =
A %>%
lapply(. %>% as.data.frame %>% add_rownames) %>%
bind_rows(.id = "product")
A_fix %>%
select(product) %>%
left_join(C_fix)