在因子内乘以单独数据帧的列(请查看)R

时间:2013-10-23 17:54:15

标签: r

v1 <- c("red", "a","b","c",1, 3, 5, 7)
v2 <- c("red", "a","b","c",1, 3, 5, 7)
v3 <- c("blue", "a","b","d",2, 4, 6, 8)
v4 <- c("blue", "a","b","d",2, 4, 6, 8)
v5 <- c("blue", "a","b","d",2, 4, 6, 8)

df1 <- data.frame(rbind(v1,v2,v3,v4,v5))

v6 <- c("red", 2,2,4,2)
v7 <- c("blue",1,1,0,1)

df2 <- data.frame(rbind(v6,v7))
colnames(df2) <- c("Y1", "Y2", "Y3", "Y4", "Y5")

> df1
         X1 X2 X3 X4 X5 X6 X7 X8
    v1  red  a  b  c  1  3  5  7
    v2  red  a  b  c  1  3  5  7
    v3 blue  a  b  d  2  4  6  8
    v4 blue  a  b  d  2  4  6  8
    v5 blue  a  b  d  2  4  6  8




  > df2
     Y1 Y2 Y3 Y4 Y5
v6  red  2  2  4  2
v7 blue  1  1  0  1

如何从df2获取4个数字列并将它们在因子(红色,蓝色)和列(分别)中相乘?假设我想要(v6,X2)并将其乘以(v1:v2,X5)。

如果您需要进一步澄清我想要做的事情,请询问。

编辑:为了澄清,我想在上面的例子中进行所有可能的乘法。

edit2:已编辑的colnames

1 个答案:

答案 0 :(得分:1)

如果我理解你的目标,这里有两种可能的解决方案。您可以使用match

> df3<-df1
> df3[,5:8]<-df3[,5:8]*df2[match(df1[,1],df2[,1]),2:5]
> df3
     X1 X2 X3 X4 X5 X6 X7 X8
v1  red  a  b  c  2  6 20 14
v2  red  a  b  c  2  6 20 14
v3 blue  a  b  d  2  4  0  8
v4 blue  a  b  d  2  4  0  8
v5 blue  a  b  d  2  4  0  8

或者您可以使用merge

> df3<-merge(df1,df2,by=1)
> df3[,5:8]<-df3[,5:8]*df3[,9:12]
> df3[,1:8]
    X1 X2 X3 X4 X5 X6 X7 X8
1 blue  a  b  d  2  4  0  8
2 blue  a  b  d  2  4  0  8
3 blue  a  b  d  2  4  0  8
4  red  a  b  c  2  6 20 14
5  red  a  b  c  2  6 20 14