[R] creating a new column with values from another

Patrick Connolly p_connolly at slingshot.co.nz
Tue Sep 13 10:17:51 CEST 2011


On Mon, 12-Sep-2011 at 12:35PM -0700, holly shakya wrote:

|> I have 2 columns for weight. There are NAs in each column but not for the
|> same observation. Some observations have values for both.  I would want to
|> prioritize the WT2 values so I would like to do the following:
|> 
|> >From this:
|> ID          WT1    WT2
|> 1           134      NA
|> 2           145       155
|> 1            NA      175
|> 3            NA      187
|> 
|> To this:
|> ID    WT1       WT2    WT
|> 1        NA         175     175
|> 2      145         155      155
|> 3       NA         187      187
|> 
|> Populating the NA values of wt2 with those of wt1 would work as well. Any
|> suggestions would be greatly appreciated.

If xx is your dataframe, and the NAs are as you describe, this will
get you close to what you want.

> xx <- within(xx, WT <- WT2)
> xx <- within(xx, WT[is.na(WT2)] <- WT1[is.na(WT2)])
> aggregate(WT ~ ID, function(x) max(x), data = xx)

  ID  WT
1  1 175
2  2 155
3  3 187


You're almost there.




|> -- 
|> Holly Shakya
|> 
|> Doctoral Student
|> San Diego State University/University of California, San Diego
|> Joint Doctoral Program in Public Health
|> (Global Health)
|> 
|> 	[[alternative HTML version deleted]]
|> 
|> ______________________________________________
|> R-help at 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.

-- 
~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.   
   ___    Patrick Connolly   
 {~._.~}                   Great minds discuss ideas    
 _( Y )_  	         Average minds discuss events 
(:_~*~_:)                  Small minds discuss people  
 (_)-(_)  	                      ..... Eleanor Roosevelt
	  
~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.



More information about the R-help mailing list