![](/img/trans.png)
[英]R: count how many elements of a vector are are present in each sublist of a nested list
[英]Adding a vector to each sublist within a list R
我有兩個具有相同結構的列表。 我想將它們組合起來以產生以下所需的輸出。
A <- list(c(1,2,3,2,1,4),c(7,3,1,2,2,1),c(2,3,7,2,2,8))
B <- list(c(2,1,3,2),c(3,1,5,2),c(2,4,5,1))
# Desired Output
[[1]]
[1] 1 2 3 2 1 4
[1] 2 1 3 2
[[2]]
[1] 7 3 1 2 2 1
[1] 3 1 5 2
[[3]]
[1] 2 3 7 2 2 8
[1] 2 4 5 1
# I have tried with the items beloww and nothing works as to produce the shown desired output. Would you happen to know on how to combine the two vectors as to produce the outcome below.
c
cbind(A,B)
A B
[1,] Numeric,6 Numeric,4
[2,] Numeric,6 Numeric,4
[3,] Numeric,6 Numeric,4
merge
append
由於“A”和“B”中相應list
元素的長度不同,我們可以將其保留在list
。 一個方便的功能是Map
在“A”和“B”的相應list
元素上執行此操作。
lst <- Map(list, A, B)
如果我們要保持這個作為一個matrix
與NA
墊不等長,一個選項是stri_list2matrix
從library(stringi)
輸出將是一個matrix
,但我們需要將character
輸出轉換回numeric
library(stringi)
lst1 <- lapply(lst, stri_list2matrix, byrow=TRUE)
lapply(lst1, function(x) matrix(as.numeric(x),nrow=2))
#[[1]]
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 1 2 3 2 1 4
#[2,] 2 1 3 2 NA NA
#[[2]]
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 7 3 1 2 2 1
#[2,] 3 1 5 2 NA NA
#[[3]]
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 2 3 7 2 2 8
#[2,] 2 4 5 1 NA NA
你的'期望輸出'不是很清楚。 列表的第一個元素內部是什么? 這是另一個清單嗎?
您可以嘗試使用mapply
,並更改FUN
以獲得不同的輸出格式:
mapply(FUN = list, A, B, SIMPLIFY = FALSE)
這為您提供了列表中的列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.