在R的向量列表中减去相似命名的元素 [英] Subtracting similarly named elements in a list of vectors in R
本文介绍了在R的向量列表中减去相似命名的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有3个向量的列表,X
,Y
和Z
.我想减去这3个向量的命名类似的元素.就是说,类似地减去了类似名称的元素:X - Y - Z
.
I have a list of 3 vectors, X
, Y
, and Z
. I want to subtract similarly named elements of these 3 vectors. That is, similarly named elements subtracted throughout like so: X - Y - Z
.
此外,如果一个元素(在X
中的ChandlerA
和Trus.Hsu
)在一个矢量中仅出现一次,而在其他矢量中不出现,那么我想完全跳过该元素.
Also, if an element (here ChandlerA
and Trus.Hsu
in X
) appears only once in one vector but not in others, then I want to skip that element altogether.
我的所需输出是:
c(Bit.KnoA = -2, Bit.KnoB = -4, Bit.KnoC = -2, Ellis.etal = 3, Mubarak = 3, sheenA = 5, Shin.Ellis = 5, Sun = 7)
是否可以在 Base R 中实现这一目标?
Is it possible to achieve this in Base R?
V = list(X = c(Bit.KnoA = 4, Bit.KnoB = 1, Bit.KnoC = 2, ChandlerA = 3, Ellis.etal =4,
Mubarak=5, SheenA=6, Shin.Ellis=7 , Sun = 8, Trus.Hsu=3 ),
Y = c(Bit.KnoA = 6, Bit.KnoB = 3, Bit.KnoC = 4, Ellis.etal =1, Mubarak=2,
SheenA=1, Shin.Ellis=2 , Sun = 1),
Z = c(Bit.KnoB = 2) )
V[[1]] - V[[2]] - V[[3]] # all elements regardless of names are subtracted
推荐答案
我们可以使用aggregate
和Reduce
with(aggregate(values ~ ind, subset(do.call(rbind, lapply(V, stack)),
ind %in% names(which(table(ind) > 1))),
FUN = function(x) Reduce(`-`, x)), setNames(values, ind))
# Bit.KnoA Bit.KnoB Bit.KnoC Ellis.etal Mubarak SheenA Shin.Ellis Sun
# -2 -4 -2 3 3 5 5 7
或使用tidyverse
library(tidyverse)
map_df(V, enframe) %>%
group_by(name) %>%
filter(n() > 1) %>%
summarise(value = reduce(value, `-`)) %>%
deframe
# Bit.KnoA Bit.KnoB Bit.KnoC Ellis.etal Mubarak SheenA Shin.Ellis Sun
# -2 -4 -2 3 3 5 5 7
这篇关于在R的向量列表中减去相似命名的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文