Re: [R] Dataframe modification

From: Sachin J <sachinj.2006_at_yahoo.com>
Date: Tue 22 Aug 2006 - 04:41:39 EST


Hi Gabor,    

  Thanx for the help. I forgot to mention this. Column A is something like this    

  A <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7,8,9,10,11,12)    

  i.e it repeats. Rest all is same. How can I modify your solution to take care of this issue.    

  Thanx in advance.    

  Sachin

Gabor Grothendieck <ggrothendieck@gmail.com> wrote:   Here are two solutions:

A <- 1:8
B <- c(1,2,4,7,8)
C <- c(5,3,10,12,17)

# solution 1 - assignment with subscripting DF <- data.frame(A, B = A, C = 0)
DF[A %in% B, "C"] <- C

# solution 2 - merge
DF <- with(merge(data.frame(A), data.frame(B, C), by = 1, all = TRUE), data.frame(A, B = A, C = ifelse(is.na(C), 0, C)))

On 8/21/06, Sachin J wrote:
> Hi,
>
> How can I accomplish this in R.
>
> I have a Dataframe with 3 columns. Column B and C have same elements. But column A has more elements than B and C. I want to compare Column A with B and do the following:
>
> If A is not in B then insert a new row in B and C and fill these new rows with
> B = A and C = 0. So finally I will have balanced dataframe with equal no of rows (entries) in all the columns.
>
> For example:
>
> A[3] = 3 but is not in B. So insert new row and set B[3] = 3 (new row) and C[3] = 0. Final result would look like:
>
> A B C
> 1 1 5
> 2 2 3
> 3 3 0
> 4 4 10
> 5 5 0
> 6 6 0
> 7 7 12
> 8 8 17
>
> These are the columns of DF
> > a <- c(1,2,3,4,5,6,7,8)
> > b <- c(1,2,4,7,8)
> > c(5,3,10,12,17)
>
> Thanx in advance for the help.
>
> Sachin
>
> __________________________________________________
>
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help@stat.math.ethz.ch 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.
>


        [[alternative HTML version deleted]]



R-help@stat.math.ethz.ch 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. Received on Tue Aug 22 04:55:23 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Tue 22 Aug 2006 - 06:23:48 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.