简体   繁体   中英

R - Assign ifelse output and data.table

I'm trying to assign a datatable to a new variable based on a condition (ifelse).

When I run the first line, the data table DT2 is returned as a list and only the values of the first column of DT1. When I run the second line, the data table is correctly assigned to the variable as a data table with all columns and rows.

Why doesn't the first alternative work?

library(data.table)
DT1 = data.table(x=rep(c("a","b","c"),each=3),y=c(1,3,6), v=1:9)
n <- 1

DT2 <- ifelse(n>0, DT1, NA) # line 1
ifelse(n>0, DT2 <- DT1, NA) # line 2

The problem with ifelse is that it is vectorized, and you don't want this behavior for your logic. You may try the following workaround:

n <- 1
DT2 <- NA
if (n > 0) DT2 <- DT1

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