[R] creating a new column with values from another

Daniel Malter daniel at umd.edu
Mon Sep 12 22:36:50 CEST 2011


You can do this using ifelse(). See example below.

x<-rpois(100,100)
NA.x<-sample(1:100,40)
x[NA.x]=NA

y<-rpois(100,100)
NA.y<-sample(1:100,40)
y[NA.y]=NA

z<-ifelse(!is.na(y),y,ifelse(!is.na(x),x,NA))

HTH,
Daniel



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.
> -- 
> 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.
> 

--
View this message in context: http://r.789695.n4.nabble.com/creating-a-new-column-with-values-from-another-tp3808528p3808550.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list