[R] matrix/df help populate NA

Adrian Johnson oriolebaltimore at gmail.com
Mon Jun 15 06:58:53 CEST 2015


Thank you very much. It worked!


On Sun, Jun 14, 2015 at 8:00 PM, jim holtman <jholtman at gmail.com> wrote:
> Is this what you want:
>
>> x1 = structure(list(Subject = c("x1", "x2"), A = c(1.5, -1.2), B = c(-1.3,
> + -0.3), C = c(0.4, 0.3), D = c(-0.2, -0.1)), .Names = c("Subject",
> + "A", "B", "C", "D"), class = "data.frame", row.names = c(NA,
> + -2L))
>>
>> x2 = structure(list(Subject = c("x1", "x2"), A = c(4.3, 2.4), D = c(-2.4,
> + 0.1), F = c(1.3, 0.5), H = c(-2.3, -1.4)), .Names = c("Subject",
> + "A", "D", "F", "H"), class = "data.frame", row.names = c(NA,
> + -2L))
>>
>> # determine what the missing columns are and then add them to x2
>> missing <- setdiff(colnames(x1), colnames(x2))
>>
>> new_x2 <- x2
>>
>> for (i in missing) new_x2[[i]] <- NA
>>
>> new_x2
>   Subject   A    D   F    H  B  C
> 1      x1 4.3 -2.4 1.3 -2.3 NA NA
> 2      x2 2.4  0.1 0.5 -1.4 NA NA
>
>
>
>
>
> Jim Holtman
> Data Munger Guru
>
> What is the problem that you are trying to solve?
> Tell me what you want to do, not how you want to do it.
>
> On Sat, Jun 13, 2015 at 11:17 PM, Adrian Johnson <oriolebaltimore at gmail.com>
> wrote:
>>
>> Dear group:
>>
>> I have two data frames. The column names of the two data frame has
>> some common variables but not identical.
>>
>> my aim is to make 2  DFs more uniform by taking union of both colnames
>>
>>
>> For example: I have x1 and x2 matrices:
>>
>> > x1
>>   Subject    A    B   C    D
>> 1      x1  1.5 -1.3 0.4 -0.2
>> 2      x2 -1.2 -0.3 0.3 -0.1
>> > x2
>>   Subject   A    D   F    H
>> 1      x1 4.3 -2.4 1.3 -2.3
>> 2      x2 2.4  0.1 0.5 -1.4
>>
>>  cases = c('A','B','C','D','F','H')
>>
>> for X2 I want to create newX2 DF.
>>
>> > x3
>>   Subject   A  B  C    D   F    H
>> 1      x1 4.3 NA NA -2.4 1.3 -2.3
>> 2      x2 2.4 NA NA  0.1 0.5 -1.4
>>
>>
>> Since B and C are no existing in x2, I put NAs.
>>
>> how can I create x3 matrix?
>>
>>
>>
>> dput code:
>>
>> x1 = structure(list(Subject = c("x1", "x2"), A = c(1.5, -1.2), B = c(-1.3,
>> -0.3), C = c(0.4, 0.3), D = c(-0.2, -0.1)), .Names = c("Subject",
>> "A", "B", "C", "D"), class = "data.frame", row.names = c(NA,
>> -2L))
>>
>> x2 = structure(list(Subject = c("x1", "x2"), A = c(4.3, 2.4), D = c(-2.4,
>> 0.1), F = c(1.3, 0.5), H = c(-2.3, -1.4)), .Names = c("Subject",
>> "A", "D", "F", "H"), class = "data.frame", row.names = c(NA,
>> -2L))
>>
>>
>> Could you please help how to create x3 with NAs incorporated.
>> adrian.
>>
>> ______________________________________________
>> 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.
>
>



More information about the R-help mailing list