我是一名正在成长的 R 用户,需要帮助来解决我遇到的困难。
我很难找到适合我情况的解决方案。
I have to nested lists which I need to join together
ListA:
[abc]:
[1] 0 1 1 2
[2] 2 0 4 5
[3] 3 5 0 6
[4] 2 3 1 0
[def]
[1] 0 4 2
[2] 2 0 1
[3] 1 1 0
List B:
[abc]:
[1] 111 112 113 114
[def]:
[1] 222 223 224
这 2 个列表各自跨越 82 个表,格式相同,元素相同。这意味着我需要一个可扩展代码,它不会手动定位每个列表或元素。
I want to take the ListB, and add it as first column and first row of ListA >either as column/row names or just in the data itself like these:
ListC:
[abc]:
111 112 113 114
[111] 0 1 1 2
[112] 2 0 4 5
[113] 3 5 0 6
[114] 2 3 1 0
[def]:
222 223 224
[222] 0 4 2
[223] 2 0 1
[224] 1 1 0
我尝试过各种方法
mapply(cbind, ListB,ListA, SIMPLIFY=FALSE)
与
mapply(rbind, Listb,ListA, SIMPLIFY=FALSE)
我也尝试过
lapply(ListA, function(x){
names(x) <- ListB
df
})
还有
Map(setNames, ListA, names(ListB))
以及这些代码的各种随机迭代。
有时我可以获得列名称,但不适用于行名称(反之亦然),因为“总向量大小”不一样。
我错过了什么?将 82 个列表分成数据帧并一一手动处理(这根本不是动态的)我完全被难住了!
请让我知道我需要做什么才能完成这项工作
最佳答案
考虑用多行扩展函数调用。然后使用用户定义的方法调用Map
。
name_items <- function(elem, nm) {
colnames(elem) <- nm
rownames(elem) <- nm
return(elem)
}
newListA <- Map(name_items, ListA, ListB)
newListA <- mapply(name_items, ListA, ListB, SIMPLIFY=FALSE) # EQUIVALENT CALL
关于r - 将列名和行名添加到 R 中的列表元素中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51547683/