[R] Query - Merging and conditional replacement of values in a data frame
Bhaskar Mitra
bhaskar.kolkata at gmail.com
Sun Feb 12 20:02:38 CET 2017
Thanks for all your help. This is helpful.
Best,
Bhaskar
On Sun, Feb 12, 2017 at 4:35 AM, Jim Lemon <drjimlemon at gmail.com> wrote:
> Hi Bhaskar,
> Maybe:
>
> df1 <-read.table(text="time v1 v2 v3
> 1 2 3 4
> 2 5 6 4
> 3 1 3 4
> 4 1 3 4
> 5 2 3 4
> 6 2 3 4",
> header=TRUE)
>
>
> df2 <-read.table(text="time v11 v12 v13
> 3 112 3 4
> 4 112 3 4",
> header=TRUE)
>
> for(time1 in df1$time) {
> time2<-which(df2$time==time1)
> if(length(time2)) df1[df1$time==time1,]<-df2[time2,]
> }
>
> Jim
>
>
> On Sun, Feb 12, 2017 at 11:13 AM, Bhaskar Mitra
> <bhaskar.kolkata at gmail.com> wrote:
> > Hello Everyone,
> >
> > I have two data frames df1 and df2 as shown below. They
> > are of different length. However, they have one common column - time.
> >
> > df1 <-
> > time v1 v2 v3
> > 1 2 3 4
> > 2 5 6 4
> > 3 1 3 4
> > 4 1 3 4
> > 5 2 3 4
> > 6 2 3 4
> >
> >
> > df2 <-
> > time v11 v12 v13
> > 3 112 3 4
> > 4 112 3 4
> >
> > By matching the 'time' column in df1 and df2, I am trying to modify
> column
> > 'v1' in df1 by replacing it
> > with values in column 'v11' in df2. The modified df1 should look
> something
> > like this:
> >
> > df1 <-
> > time v1 v2 v3
> > 1 2 3 4
> > 2 5 6 4
> > 3 112 3 4
> > 4 112 3 4
> > 5 2 3 4
> > 6 2 3 4
> >
> > I tried to use the 'merge' function to combine df1 and df2 followed by
> > the conditional 'ifelse' statement. However, that doesn't seem to work.
> >
> > Can I replace the values in df1 by not merging the two data frames?
> >
> > Thanks for your help,
> >
> > Regards,
> > Bhaskar
> >
> > [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> > 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.
>
[[alternative HTML version deleted]]
More information about the R-help
mailing list