Alice Wines wrote: > > Hello all, > > I have a quandry I have been scratching my head about for a > while. I've searched the manual and the web and have not been able to > find an acceptable result, so I am hoping for some help. > > I have two data frames and I want to index into the first using > the second, and replace the specific values I have indexed with more > values from the second data.frame. I can do this using a loop, but I > wanted a quicker solution with no loops involved. > > Although my data set is much larger than this, a small example of what > I am trying to do is as follows: > > df1 <- data.frame(rows=c("A","B","C", "B", "C", "A"), > columns=c("21_2", "22_2", "23_2", "21_2", "22_2", "23_2"), > values=c(3.3, 2.5, 67.2, 44.3, 53, 66)) > df2 <- data.frame(matrix(rep(NA, length(df1$values)),nrow=3, ncol=3)) > names(df2) <- c("21_2", "22_2", "23_2") > row.names(df2) <- c("A", "B", "C") > >> df1 > rows columns values > 1 A 21_2 3.3 > 2 B 22_2 2.5 > 3 C 23_2 67.2 > 4 B 21_2 44.3 > 5 C 22_2 53.0 > 6 A 23_2 66.0 > > ....... > > What I want to see is the following: > >>df3 > 21_2 22_2 23_2 > A 3.3 NA 66.0 > B 44.3 2.5 NA > C NA 53.0 67.2 >
How about this (I have converted df2 into a matrix) df2 <- matrix(rep(NA, length(df1$values)),nrow=3, ncol=3) colnames(df2) <- c("21_2", "22_2", "23_2") rownames(df2) <- c("A", "B", "C") df2[cbind(df1$rows,df1$columns)] <- df1$values # convert df2 to a data.frame Berend-- View this message in context: http://r.789695.n4.nabble.com/indexing-into-a-data-frame-using-another-data-frame-that-also-contains-values-for-replacement-tp3487147p3487234.html Sent from the R help mailing list archive at Nabble.com. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.