如何在字符表和数字表之间建立链接?

时间:2018-04-11 14:59:06

标签: r dataframe

c1 <- c("product a1","product a2","product a3","product b1","product b2","product b3")
c2 <- matrix (c1,nrow=2,ncol=3,dimnames = list(c("productline a","productline b"),c("1","2","3")))
company1 <- c(0,1,0,0,0,0)
company2 <- c(0,0,0,1,1,0)
company3 <- c(1,1,0,0,0,0)
data1 <- data.frame(company1,company2,company3,row.names = c1)
c2            
                   1            2            3           
productline a "product a1" "product a2" "product b3"
productline b "product b1" "product b2" "product b3"   

data1
            company1 company2 company3
product a1        0        0        1
product a2        1        0        1
product a3        0        0        0
product b1        0        1        0
product b2        0        1        0
product b3        0        0        0
result
            productline a   productline b
 company1        1               0         
 company2        0               2
 company3        2               0  

我这里有一个表数据1。现在我想分析data1。并且基本信息是产品a1,a2,a3都属于&#34;产品线a&#34;产品b1,b2,b3属于&#34;产品线b&#34;,如表c2所示。

我想结合表c2和data1来获取结果表,就像我出现在那里一样。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

基础R的可能方法:

i <- which(apply(c2, 1, function(x) rownames(data1) == x), arr.ind = TRUE)

rn <- rownames(c2)[i[,2]]

aggregate(. ~ rn, data1, sum)

给出:

             rn company1 company2 company3
1 productline a        1        0        2
2 productline b        0        2        0

使用过的数据:

c1 <- c("product a1","product a2","product a3","product b1","product b2","product b3")
c2 <- matrix(c1, nrow = 2, ncol = 3, byrow = TRUE,
             dimnames = list(c("productline a","productline b"),
                             c("1","2","3")))

data1 <- data.frame(company1 = c(0,1,0,0,0,0),
                    company2 = c(0,0,0,1,1,0),
                    company3 = c(1,1,0,0,0,0),
                    row.names = c1)