简体   繁体   中英

In R, how to restrict selection and setting of cell values of data.table to list of columns?

I need to set all instances of "-1" in a subset of columns of a data.table to NA.

I can set all such instances of ALL columns in the data.table to NA as follows:

dt <- data.table(c("-1","A","A","B"), c("A","B","-1","-1"),c("-1","B","B","-1") )
for (i in seq_along(dt)) 
    set(dt, i=which(dt[[i]]=="-1"), j=i, value=NA)
> dt
   V1 V2 V3
1: NA  A NA
2:  A  B  B
3:  A NA  B
4:  B NA NA

But how do I limit the replacement to a subset of columns, eg c("V2","V3")? This doesn't work:

dt <- data.table(c("-1","A","A","B"), c("A","B","-1","-1"),c("-1","B","B","-1") )
for (i in seq_along(dt[,c("V2","V3"),with=FALSE])) 
    set(dt[,c("V2","V3"),with=FALSE], i=which(dt[,c("V2","V3"),with=FALSE][[i]]=="-1"), j=i, value=NA)
dt
> dt
V1 V2 V3
1: -1  A -1
2:  A  B  B
3:  A -1  B
4:  B -1 -1

We can loop through the index of names and set the elements that are -1 in those columns to NA.

for(j in paste0('V', 2:3)){
 set(dt, i=which(dt[[j]]==-1), j=j, value=NA)
}

dt
#   V1 V2 V3
#1: -1  A NA
#2:  A  B  B
#3:  A NA  B
#4:  B NA NA

EDIT: Modified based on @Frank's comments.

Here is a way without using a for loop:

dt <- data.table(c("-1","A","A","B"), c("A","B","-1","-1"), c("-1","B","B","-1") )

dt$V2 = ifelse(dt$V2 == "-1", NA, dt$V2)
dt$V3 = ifelse(dt$V3 == "-1", NA, dt$V3)

dt




   V1 V2 V3
1: -1  A NA
2:  A  B  B
3:  A NA  B
4:  B NA NA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM