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 

How do I take the 4 numeric columns from df2 and multiply them within factor(red, blue) and within column (respectively)? Say I would want to take (v6, X2) and multiply it by (v1:v2,X5).

If you need further clarification of what I am trying to do please ask.

edit: For clarification, I want to make all possible multiplications of above example.

edit2: edited colnames

6
  • The fact that you have identical column names between two data frames but different variables in each will greatly complicate your problem. Commented Oct 23, 2013 at 18:10
  • column names are irrelevant.. use df1[,#] or change them if you want Commented Oct 23, 2013 at 18:11
  • No they're not, because you're going to need to merge the two data frames to do what you want efficiently. Commented Oct 23, 2013 at 18:14
  • @SeñorO, why not use suffixes in the merge? Commented Oct 23, 2013 at 18:15
  • 1
    Separate note, that is not how you build a data.frame. All items in v1 (and other rows) are converted to characters. You end up with a data.frame where each column is a factor... Commented Oct 23, 2013 at 18:19

1 Answer 1

1

If I understand your objective correctly, here are two possible solutions. You can use 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 

Or you can use 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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.