Rnewbie
2009-Aug-06 16:41 UTC
[R] problem with recording numeric output into another dataframe
dear all, I have two dataframes dataframe1 ID a b c dataframe2 ID value a;W 100 X;c 200 Y;Z 300 I wanted to match the IDs from the two dataframes and record the values into a new column of dataframe1 at the corresponding rows. This is what I expect: dataframe1 ID value a 100 b c 200 I tried doing it like this: for (i in seq(1:nrow(dataframe1))) { dataframe1[i,"value"]<-dataframe2[grep(dataframe1[i,"ID"], dataframe2$ID),"value"] } but I failed. I was able to extracted the values from dataframe2 but not able to record the values in the corresponding rows of dataframe1. I would appreciate any suggestions. Thanks in advance. Jim -- View this message in context: http://www.nabble.com/problem-with-recording-numeric-output-into-another-dataframe-tp24850155p24850155.html Sent from the R help mailing list archive at Nabble.com.
Henrique Dallazuanna
2009-Aug-06 21:03 UTC
[R] problem with recording numeric output into another dataframe
Try this: g <- sapply(DF1$ID, grep, x = DF2$ID) transform(DF2[unlist(g),],ID = DF1$ID[which(g > 0)]) On Thu, Aug 6, 2009 at 1:41 PM, Rnewbie <xuancj@yahoo.com> wrote:> > dear all, > > I have two dataframes > > dataframe1 > ID > a > b > c > > dataframe2 > ID value > a;W 100 > X;c 200 > Y;Z 300 > > I wanted to match the IDs from the two dataframes and record the values > into > a new column of dataframe1 at the corresponding rows. This is what I > expect: > > dataframe1 > ID value > a 100 > b > c 200 > > I tried doing it like this: > > for (i in seq(1:nrow(dataframe1))) { > dataframe1[i,"value"]<-dataframe2[grep(dataframe1[i,"ID"], > dataframe2$ID),"value"] > } > > but I failed. I was able to extracted the values from dataframe2 but not > able to record the values in the corresponding rows of dataframe1. > > I would appreciate any suggestions. Thanks in advance. > > Jim > -- > View this message in context: > http://www.nabble.com/problem-with-recording-numeric-output-into-another-dataframe-tp24850155p24850155.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. >-- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O [[alternative HTML version deleted]]