Skip to content
Prev 309776 / 398506 Next

Replacing NAs in long format

Hi,
May be this helps:
dat2<-read.table(text="
idr? schyear? year
1??????? 4????????? -1
1??????? 5??????????? 0
1??????? 6??????????? 1
1??????? 7??????????? 2
2??????? 9??????????? 0
2??????? 10??????????? 1
2??????? 11????????? 2
",sep="",header=TRUE)

?dat2$flag<-unlist(lapply(split(dat2,dat2$idr),function(x) rep(ifelse(any(apply(x,1,function(x) x[2]<=5 & x[3]==0)),1,0),nrow(x))),use.names=FALSE)
?dat2
#? idr schyear year flag
#1?? 1?????? 4?? -1??? 1
#2?? 1?????? 5??? 0??? 1
#3?? 1?????? 6??? 1??? 1
#4?? 1?????? 7??? 2??? 1
#5?? 2?????? 9??? 0??? 0
#6?? 2????? 10??? 1??? 0
#7?? 2????? 11??? 2??? 0
A.K.




----- Original Message -----
From: Christopher Desjardins <cddesjardins at gmail.com>
To: jim holtman <jholtman at gmail.com>
Cc: r-help at r-project.org
Sent: Saturday, November 3, 2012 7:09 PM
Subject: Re: [R] Replacing NAs in long format

I have a similar sort of follow up and I bet I could reuse some of this
code but I'm not sure how.

Let's say I want to create a flag that will be equal to 1 if schyear? < = 5
and year = 0 for a given idr. For example
idr?  schyear?  year
1? ? ? ?  4? ? ? ? ?  -1
1? ? ? ?  5? ? ? ? ? ? 0
1? ? ? ?  6? ? ? ? ? ? 1
1? ? ? ?  7? ? ? ? ? ? 2
2? ? ? ?  9? ? ? ? ? ? 0
2? ? ? ? 10? ? ? ? ? ? 1
2? ? ? ? 11? ? ? ? ?  2

How could I make the data look like this?

idr?  schyear?  year?  flag
1? ? ? ?  4? ? ? ? ?  -1? ?  1
1? ? ? ?  5? ? ? ? ? ? 0? ?  1
1? ? ? ?  6? ? ? ? ? ? 1? ?  1
1? ? ? ?  7? ? ? ? ? ? 2? ?  1
2? ? ? ?  9? ? ? ? ? ? 0? ?  0
2? ? ? ? 10? ? ? ? ? ? 1? ? 0
2? ? ? ? 11? ? ? ? ?  2? ?  0


I am not sure how to end up not getting both 0s and 1s for the 'flag'
variable for an idr. For example,

dat$flag = ifelse(schyear <= 5 & year ==0, 1, 0)

Does not work because it will create:

idr?  schyear?  year?  flag
1? ? ? ?  4? ? ? ? ?  -1? ?  0
1? ? ? ?  5? ? ? ? ? ? 0? ?  1
1? ? ? ?  6? ? ? ? ? ? 1? ?  0
1? ? ? ?  7? ? ? ? ? ? 2? ?  0
2? ? ? ?  9? ? ? ? ? ? 0? ?  0
2? ? ? ? 10? ? ? ? ? ? 1? ? 0
2? ? ? ? 11? ? ? ? ?  2? ?  0

And thus flag changes for an idr. Which it shouldn't.

Thanks,
Chris


On Sat, Nov 3, 2012 at 5:50 PM, Christopher Desjardins <
cddesjardins at gmail.com> wrote:

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