Hi, I have a data frame which contains two fields, 'prev' and 'mchnum'. I have another data frame which also contains 'mchnum' and 'prev' and some other fields. The 'prev' data in this field is corrupted and I want to replace it with the data from the other data frame for matching values of 'mchnum' (which are unique). Is there an easier way of doing this than having two for loops and going through each field looking for matching values of 'mchnum' and then replacing the 'prev' value when they match. Thanks Neil
Gabor Grothendieck
2004-Oct-20 03:54 UTC
[R] Replacing data from one data frame to another
Check out the merge command. From: Neil Leonard <nleonard at tartarus.uwa.edu.au> Hi, I have a data frame which contains two fields, 'prev' and 'mchnum'. I have another data frame which also contains 'mchnum' and 'prev' and some other fields. The 'prev' data in this field is corrupted and I want to replace it with the data from the other data frame for matching values of 'mchnum' (which are unique). Is there an easier way of doing this than having two for loops and going through each field looking for matching values of 'mchnum' and then replacing the 'prev' value when they match. Thanks Neil
Using merge() on 'mchnum' will give you a data frame with 'prev' from each. You can also use match directly. Suppose your dfs are A and B. I think you want ind <- match(B$mchnum, A$mchnum) B$prev <- A$prev[ind] On Wed, 20 Oct 2004, Neil Leonard wrote:> I have a data frame which contains two fields, 'prev' and 'mchnum'. > > I have another data frame which also contains 'mchnum' and 'prev' and > some other fields. The 'prev' data in this field is corrupted and I > want to replace it with the data from the other data frame for matching > values of 'mchnum' (which are unique). Is there an easier way of doing > this than having two for loops and going through each field looking for > matching values of 'mchnum' and then replacing the 'prev' value when > they match.-- Brian D. Ripley, ripley at stats.ox.ac.uk Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UK Fax: +44 1865 272595