如何在R中合并表? [英] How to merge tables in R?

查看:70
本文介绍了如何在R中合并表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这将是一个简单的答案,但我无法解决!这是使用iris数据集的示例:

I think this will have a simple answer, but I can't work it out! Here is an example using the iris dataset:

a <- table(iris[,2])
b <- table(iris[,3]) 

如何将这两个表加在一起?例如,在新的输出表中,变量3的值为27(26 + 1),变量3.3的值为8(6 + 2).

How do I add these two tables together? For example, the variable 3 would have a value of 27 (26+1) and variable 3.3 a value of 8 (6+2) in the new output table.

任何帮助,不胜感激.

Any help much appreciated.

推荐答案

如果要使用在ab中都存在的变量,这将起作用:

This will work if you want to use the variables which are present in both a and b:

n <- intersect(names(a), names(b))
a[n] + b[n]

#  3 3.3 3.5 3.6 3.7 3.8 3.9   4 4.1 4.2 4.4 
# 27   8   8   5   4   7   5   6   4   5   5


如果要使用所有变量:


If you want to use all variables:

n <- intersect(names(a), names(b)) 

res <- c(a[!(names(a) %in% n)], b[!(names(b) %in% n)], a[n] + b[n])

res[order(names(res))] # sort the results

这篇关于如何在R中合并表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆