简体   繁体   中英

R: Implementation of an if statement in a for loop

The data.frame xy contains numeric data and data_qual contains qualitative data which I want to include in a for loop with an if statement (commented out in the code below).

The if statement should be applied if the ID in data_qual$ID is the same than in xy$ID .

I am trying to make it independent by doing this:

if(i$ID %in% data_qual[data_qual$ID %in% i$ID,]$ID){...}

but it doesn't work when I incorporate it in the for loop. The logical result is correct but it only works for the first element when implemented in the for loop. Can anyone see what I am doing wrong here?

My code:

xy <- data.frame(NAME=c("NAME1","NAME1","NAME1","NAME2","NAME2","NAME2","NAME3","NAME3"),ID=c(87,87,87,199,199,199,233,233), X_START_YEAR=c(1950,1988,1994,1899,1909,1924,1945,1948),Y_START_VALUE=c(75,25,-90,-8,-55,-10,-9,12),X_END_YEAR=c(1985,1994,1999,1904,1924,1987,1946,1949), Y_END_VALUE=c(20,50,-15,-70,-80,-100,24,59))

data_qual <- data.frame(NAME=c("NAME2","NAME3"),ID=c(199,233),X_START_YEAR=c(1986,1905), Y_START_VALUE=c("-X","ST"),X_END_YEAR=c(1987,1907),Y_END_VALUE=c("-X","ST"))

# split xy by group as defined by ID
ind <- split(xy,xy$ID)

for (i in ind){xx = unlist(i[,grep('X_',colnames(i))]) 
               yy = unlist(i[,grep('Y_',colnames(i))]) 
               fname <- paste0(i[1, 'ID'], '.png') 
               png(fname, width=1679, height=1165, res=150)
  if(any(xx < 1946)) {my_x_lim <- c(min(xx), 2014)} else {my_x_lim <- c(1946, 2014)} 
  par(mar=c(6,8,6,5))
  plot(xx, yy,main=unique(i[,1]),xlab="Time [Years]",ylab="Value [m]",pch=21,xlim = my_x_lim,font.lab=2, cex.lab=1.2, cex.axis=1.1)
  i <- i[,-1]
  segments(i[,2],i[,3],i[,4],i[,5],lwd=2)

 # if(i$ID %in% data_qual[data_qual$ID %in% i$ID,]$ID){
 #     rel_data_qual <- data_qual[data_qual$ID %in% i$ID,]
 #     text(x = rel_data_qual$X_END_YEAR,
 #          y = min(i$Y_END_VALUE + 3),
 #     labels = rel_data_qual$Y_END_VALUE)  
 #   }

  dev.off()
}  

我没有足够的代表对此发表评论,但是我使用了一条打印语句来测试您的代码,除了romantsegelskyi提到的易于补救的警告(我使用的是R version 3.1.1 (2014-07-10) x86_64-pc-linux-gnu

我想你,你想做的是

if (i$ID[1] %in% data_qual%ID) {...}

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