r语言 - 如何在字符表和数字表之间建立链接


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。现在我想分析数据1。而基本信息是产品a1,a2,a3都属于"产品线a",产品b1,b2,b3属于"产品线b",如表c2所示。

我想结合表 c2 和 data1 来获得结果表,就像我在那里显示的那样。

我该怎么做?

基本 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)

相关内容

最新更新