dataframe - Multiply column values in one data.frame by column in another data.frame on a condition in R -


i have 2 data frames in r trying combine based on values in column each.

df1=data.frame(comp=c("comp1", "comp2", "comp3","comp1"),  state1=c(1,0,0,1),  state2=c(1,1,0,1),  state3=c(0,1,1,0),  state4=c(0,0,1,0),year=c(1,1,1,2))     comp state1 state2 state3 state4 year 1 comp1      1      1      0      0    1 2 comp2      0      1      1      0    1 3 comp3      0      0      1      1    1 4 comp1      1      1      0      0    2  df2=data.frame(state=c("state1","state2", "state3", "state4",                         "state1","state2", "state3", "state4"),   var1=c(1,0,0,1,0,0,1,1),   var2=c(0,1,0,0,0,1,1,0),   year=c(1,1,1,1,2,2,2,2)) 

df2

    state var1 var2 year 1 state1    1    0    1 2 state2    0    1    1 3 state3    0    0    1 4 state4    1    0    1 5 state1    0    1    2 6 state2    0    1    2 7 state3    1    1    2 8 state4    1    0    2 

i'd append columns df1 var1, var2 mean of states comp.

so, var1 comp1 should 1*1+1*0+0*0+0*1/(1+1) or state*var/sum(state comp) year.

df3 like:

         state1 state2 state3 state4 year  var1  var2     1 comp1  1      1      0      0     1   0.5   0.5     2 comp2  0      1      1      0     1   0.0   0.5     3 comp3  0      0      1      1     1   0.5   0.0     4 comp1  1      1      0      0     2   0.5   1.0 

is possible? tried use ddply mean of var1, summarizing comp , year, doesn't work. end more 1 row per comp per year.

thanks in advance. 1 similar problem, doesn't show conditional in second data set. multiply various subsets of data frame different vectors

please advise.

my hope breaking segments can find out why results different prediction:

 df3 <- matrix(na, ncol=2, nrow=nrow(df1))  (i in seq(nrow(df1))) {      df3[i, 1] <- sum(df2[ df2$year==df1$year[i], "var1"] * df1[i, 2:5])      df3[i, 2] <- sum(df2[ df2$year==df1$year[i], "var2"] * df1[i, 2:5])  }  m4<-df3/rowsums(df1[2:5])  cbind(df1, m4) #---------------    comp state1 state2 state3 state4 year   1         2 1 comp1      1      1      0      0    1 0.5 0.5000000 2 comp2      0      1      1      0    1 0.0 0.3333333 3 comp3      0      0      1      1    1 0.5 0.0000000 4 comp1      1      1      0      0    2 0.0 0.3333333 

seems match ok on "var1" entries , i'm hoping threw in guesses "var2".


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -