开发者

How can set NA to every 3 other data in a dataframe?

Another rather basic question for which I can't find a definitive answer online:

Suppose I have a dataset like this

开发者_开发问答
dat<-c(1,2,3,4,5,6,7,8,9,10)

I want to change the dat to

datnew<-c(1,2,3,NA,NA,NA,7,8,9,NA)

Basically just to replace every 3 data with NA across a big data frame.

Thanks,


Create an appropriate index via rep():

R> foo <- 1:10
R> foo
 [1]  1  2  3  4  5  6  7  8  9 10
R> ind <- rep(c(FALSE, TRUE), each=3)
R> ind
 [1] FALSE FALSE FALSE  TRUE  TRUE  TRUE
R> foo[ind] <- NA
R> foo
 [1]  1  2  3 NA NA NA  7  8  9 NA
R> 

Recycling helps you here as the index you created gets applied as often as needed for your data vector.

Edit: Also show ind above.


I thought there was a better way, but I was wrong, as Dirk pointed it to me. Below I fixed my answer, but mine is cleary worse than Dirk's answer.

foo[c(seq(4,length(foo),6),seq(5,length(foo),6),seq(6,length(foo),6))] <- NA

If it is really a data frame, then you have to specify the row where you want to aplly it and use another command to get the number of elements (like dim(dat)[1]).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜