简体   繁体   中英

& Statement in IF loop does not work

I really dont know what I am doing wrong.

This code does not work in R Studio (I have tried multiple little changes but to no avail):

Data3$Rebound3<-0
for (i in 2:length(Data3)){
  if((Data3$etype[i] == 'SHOT') && (Data3$etype[i-1] == 'SHOT')){
    Data3$Rebound3[i]<-1}}

But these 2 codes work:

Data3$Rebound3<-0
for (i in 2:length(Data3)){
  if(Data3$etype[i] == 'SHOT'){
    Data3$Rebound3[i]<-1}}

Data3$Rebound3<-0
for (i in 2:length(Data3)){
  if(Data3$etype[i-1] == 'SHOT'){
    Data3$Rebound3[i]<-1}}

Thanks in Advance for Help!

You could do this without a for loop

 indx <- with(Data3, c(FALSE,etype[-1]=='SHOT' & etype[-nrow(Data3)]=='SHOT'))
 Data3$Rebound3 <- indx+0
 head(Data3)
 #           etype Rebound3
 #1           SHOT        0
 #2           SHOT        1
 #3 SOMETHING ELSE        0
 #4      SOMETHING        0
 #5      SOMETHING        0
 #6 SOMETHING ELSE        0

Regarding your code, the 2:length(Data3) will be giving the column index instead of the row index (if I understand from your code). I guess you want the row index. Perhaps,

Data3$Rebound3<-0
for(i in 2:nrow(Data3)){
     if(Data3$etype[i] == 'SHOT' & Data3$etype[i-1] == 'SHOT'){
         Data3$Rebound3[i]<-1
     }
   }

Data3$Rebound3
#[1] 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0

data

 set.seed(24)
 Data3 <- data.frame(etype=sample(c('SHOT', 'SOMETHING', 'SOMETHING ELSE'),
                 20, replace=TRUE))

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