ItGo.me Focus on IT Recommend

Home > r - How to replace first n1 and last n2 rows with NA in specific columns

r - How to replace first n1 and last n2 rows with NA in specific columns

2021腾讯云限时秒杀,爆款1核2G云服务器298元/3年!(领取2860元代金券),
地址https://cloud.tencent.com/act/cps/redirect?redirect=1062

2021阿里云最低价产品入口+领取代金券(老用户3折起),
入口地址https://www.aliyun.com/minisite/goods

Given the following example:

library(data.table)
mat <- data.table(x = c(1:10), y = c(11:20), z = c(21:30))

cut.head <- c(0, 2, 1) 
cut.tail <- c(3, 1, 2) 

cut.head represents the number of rows that each column will be NA from top.

cut.tail represents the number of rows that each column will be NA from last.

For example, if cut.head is used, 1st and 2nd rows of column y will be NAs, as well as the 1st column of z

I would like the return as follows:

     x  y  z
 1:  1 NA NA
 2:  2 NA 22
 3:  3 13 23
 4:  4 14 24
 5:  5 15 25
 6:  6 16 26
 7:  7 17 27
 8: NA 18 28
 9: NA 19 NA
10: NA NA NA

Thank you

r data.table
|
  this question
edited Jul 9 '14 at 8:51 Matt Dowle 37.8k 10 98 163 asked Jul 9 '14 at 7:33 newbie 300 1 11

 | 

1 Answers
1

---Accepted---Accepted---Accepted---

I'd just use a for loop with := (or set()) so it's fast and (fairly) easy to read.

> for (i in 1:3) mat[seq_len(cut.head[i]), (i):=NA]
> mat
     x  y  z
 1:  1 NA NA
 2:  2 NA 22
 3:  3 13 23
 4:  4 14 24
 5:  5 15 25
 6:  6 16 26
 7:  7 17 27
 8:  8 18 28
 9:  9 19 29
10: 10 20 30

Notice that the LHS of := accepts column numbers as well as names. As an aside, this is valid :

DT[, 2:=2]   # assign 2 to column 2

Wrapping the LHS of := with parenthesis, (i):=NA, tells it to use the variable's value rather than its name.

For the tail I first tried the following but .N isn't available in i. I've added that as a feature request, FR#724.
UPDATE: Now added to v1.9.3 on 11 Jul 2014

for (i in 1:3) mat[.N+1-seq_len(cut.tail[i]), (i):=NA]
# .N now works in i
> mat
     x  y  z
 1:  1 NA NA
 2:  2 NA 22
 3:  3 13 23
 4:  4 14 24
 5:  5 15 25
 6:  6 16 26
 7:  7 17 27
 8: NA 18 28
 9: NA 19 NA
10: NA NA NA
>

We no longer have to live with a repetition of the symbol mat :

> for (i in 1:3) mat[nrow(mat)+1-seq_len(cut.tail[i]), (i):=NA]

|
  this answer
edited Jul 11 '14 at 2:39 answered Jul 9 '14 at 8:47 Matt Dowle 37.8k 10 98 163

 | 

Recommend:r - How to replace specific parts of rows in dataframe for NA

)base2<-cbind(base,base1) What i need is to change a part of each row for NAs, based on the first 2 columns (the numbers in each column show wich columns of that row need to be changed to NA. So the first row would be something like this:

------splitte line----------------------------