0
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:编辑的列名

4

1 回答 1

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
于 2013-10-23T18:30:46.823 回答