简体   繁体   中英

How can I set a variable to zero when it is numeric(0)?

data <-data.frame(i.1=c(rep(6,5)),i.2=c(6,7,7,7,8),j.1=c(11,11,11,13,9),j.2=c(11,11,12,13,9),freq=c(0.1,0.2,0.5,0.1,0.1))

   i.1 i.2 j.1 j.2 freq
1   6   6  11  11  0.1
2   6   7  11  11  0.2
3   6   7  11  12  0.5
4   6   7  13  13  0.1
5   6   8   9   9  0.1

p1 <- data[data[,1] == 6 & data[,2] == 6 & data[,3] == 7 & data[,4] == 7,]$freq

p1 - 5 is not equal to -5, since p1 is not zero, but numeric(0).

In this case, is p1 defined?

exists("p1")
[1] TRUE

How can I make it equal to zero?

I solved that by doing

if(!length(p1)) {p1 <-0}

as suggested by Ananda Mahto and DWin in the comments above.

Thanks!

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