cbind值到R中的子列表
cbind values to sublists in R
我在列表中有两个矩阵:
colList <- list()
colList[["V1"]] <- as.matrix(c("asd", "asd", "asd"))
colList[["V2"]] <- as.matrix(c("das", "das", "das"))
我想将 data.frame value.frame$keyID
的值绑定到每个子列表。第一个值(2000)到第一个子列表,第二个值(3000)到第二个子列表。
这里是value.frame:
value.frame <- data.frame(keyID =c("2000", "3000"))
结果应如下所示:
colList <- list()
colList[["V1"]] <- matrix(c("asd", "asd", "asd", 2000, 2000, 2000),
nrow=3,
ncol=2)
colList[["V2"]] <- matrix(c("das", "das", "das", 3000, 3000, 3000),
nrow=3,
ncol=2)
我用下面的代码试了一下,结果不是我想要的。希望可以有人帮帮我。
mapply( cbind, colList, paste(value.frame[,1]))
使用 lapply
和 seq_along
nms <- names(colList)
colList <- lapply(seq_along(colList), x=colList,
y=as.character(value.frame$keyID), function(j, x, y) {
cbind(x[[j]], y[j])
})
names(colList) <- nms
colList[["V1"]]
[,1] [,2]
[1,] "asd" "2000"
[2,] "asd" "2000"
[3,] "asd" "2000"
colList[["V2"]]
[,1] [,2]
[1,] "das" "3000"
[2,] "das" "3000"
[3,] "das" "3000"
您可以通过 mapply
使用选项 SIMPLIFY=FALSE
来完成此操作
mapply(cbind, colList, as.character(value.frame$keyID), SIMPLIFY=FALSE)
#$V1
# [,1] [,2]
#[1,] "asd" "2000"
#[2,] "asd" "2000"
#[3,] "asd" "2000"
#$V2
# [,1] [,2]
#[1,] "das" "3000"
#[2,] "das" "3000"
#[3,] "das" "3000"
或使用 Map
,它是 mapply(..., SIMPLIFY=FALSE)
的包装器
Map(cbind, colList, as.character(value.frame$keyID))
我在列表中有两个矩阵:
colList <- list()
colList[["V1"]] <- as.matrix(c("asd", "asd", "asd"))
colList[["V2"]] <- as.matrix(c("das", "das", "das"))
我想将 data.frame value.frame$keyID
的值绑定到每个子列表。第一个值(2000)到第一个子列表,第二个值(3000)到第二个子列表。
这里是value.frame:
value.frame <- data.frame(keyID =c("2000", "3000"))
结果应如下所示:
colList <- list()
colList[["V1"]] <- matrix(c("asd", "asd", "asd", 2000, 2000, 2000),
nrow=3,
ncol=2)
colList[["V2"]] <- matrix(c("das", "das", "das", 3000, 3000, 3000),
nrow=3,
ncol=2)
我用下面的代码试了一下,结果不是我想要的。希望可以有人帮帮我。
mapply( cbind, colList, paste(value.frame[,1]))
使用 lapply
和 seq_along
nms <- names(colList)
colList <- lapply(seq_along(colList), x=colList,
y=as.character(value.frame$keyID), function(j, x, y) {
cbind(x[[j]], y[j])
})
names(colList) <- nms
colList[["V1"]]
[,1] [,2]
[1,] "asd" "2000"
[2,] "asd" "2000"
[3,] "asd" "2000"
colList[["V2"]]
[,1] [,2]
[1,] "das" "3000"
[2,] "das" "3000"
[3,] "das" "3000"
您可以通过 mapply
使用选项 SIMPLIFY=FALSE
mapply(cbind, colList, as.character(value.frame$keyID), SIMPLIFY=FALSE)
#$V1
# [,1] [,2]
#[1,] "asd" "2000"
#[2,] "asd" "2000"
#[3,] "asd" "2000"
#$V2
# [,1] [,2]
#[1,] "das" "3000"
#[2,] "das" "3000"
#[3,] "das" "3000"
或使用 Map
,它是 mapply(..., SIMPLIFY=FALSE)
Map(cbind, colList, as.character(value.frame$keyID))