r加入两个列表并将它们的值相加

时间:2016-12-29 15:17:17

标签: r

我有两个列表:x,y

> x
     carlo      monte simulation      model    quantum 
        31         31          9          6          6 
> y
      model      system temperature     quantum  simulation     problem 
         15          15          15          13          13          12

我应该使用什么功能来获取:

simulation     model   quantum
        22        21        19

我尝试在示例中合并它们,但它给了我一个错误:

merge(x,y,by=intersect(names(x),names(y)))产生:

  

fix.by(by.x,x)出错:''必须指定唯一有效的列

该函数中没有任何关于如何处理值的论据。什么是最好的功能?

intersect(names(x),names(y))会给出结果列表的名称,但是如何将值汇总在一起?

3 个答案:

答案 0 :(得分:4)

您可以使用基数R中的Map来返回列表。

Map("+", x[intersect(names(x),names(y))], y[intersect(names(x),names(y))])
$simulation
[1] 22

$model
[1] 21

$quantum
[1] 19

mapply返回一个可能更有用的命名向量。

mapply("+", x[intersect(names(x),names(y))], y[intersect(names(x),names(y))])
simulation      model    quantum 
        22         21         19

使用[intersect(names(x), names(y))]不仅将x和y的内容子集化为具有相交名称的内容,还将正确对操作的元素进行排序。

数据

x <- list(carlo=1, monte=2, simulation=9, model=6, quantum=6)
y <-list(model=15, system=8, temperature=10, quantum=13, simulation=13, problem="no")

答案 1 :(得分:2)

简单的名称匹配就可以了:

# subset those from x which have names in y also
x1 = x[names(x)[names(x) %in% names(y)]]
# x1
# simulation      model    quantum 
#          9          6          6 

# similarily do it for y. note the order of names might be different from that in x
y1 = y[names(y)%in%names(x1)]
# y1
#  model    quantum simulation 
#     15         13         13 

# now order the names in both and then add. 
x1[order(names(x1))]+y1[order(names(y1))]
# model    quantum simulation 
#    21         19         22 

答案 2 :(得分:1)

只要您的字段有意义,基本函数merge()就可以执行此操作而不会出现问题,但您需要包含merge(..., all=TRUE),如下所示:

y <- data.frame(rbind(c(15,15,15,13,13,12)))
names(y) <- c("model","system","temperature","quantum","simulation","problem")
x <- data.frame(rbind(c(31,31,9,6,6)))
names(x) <- c("carlo","monte","simulation","model","quantum")

merge(x, y, by = c("simulation","model","quantum"), all = TRUE)

结果:

simulation model quantum carlo monte system temperature problem
1          9     6       6    31    31     NA          NA      NA
2         13    15      13    NA    NA     15          15      12

这里实际上有长度为1的数据帧,而不是列表。