简体   繁体   中英

R: For loop only works when manually executed

so I have a dataframe with four number colums A,B,C and D

I now wrote a for-loop to change values row by row when certain conditions are met.

but nothing happens, If I manually set k=1, k=2? k=3 and run the two if functions in the loop manually it works! This seems like a bug to me?

for (k in nrow(list)) {

if(list$A[k]>list$C[k]) {list$C[k]=list$A[k]}
  
if(list$B[k]<list$D[k]) {list$D[k]=list$B[k]}

}

list

Example:

A          B           C          D
195679832  197768053   195000001  197500000
195679832  197768053   197500001  200000000
227573015  228592110   227500001  230000000
64199445   65230121    65000001   67500000

should become


A          B           C           D
195679832  197768053   195679832  197500000
195679832  197768053   197500001  197768053
227573015  228592110   227573015  228592110
64199445   65230121    64199445   65000000
64199445   65230121    65000001   65230121

again: when I manually increase k and run the content of the loop one by one it works just fine, but if i run the loop as a whole it wont execute the if clauses anymore. It gives no error message aswell.

You forgott the 1: before nrow(list) . k was only receiving 4, not 1:4.

for (k in 1:nrow(list)) {

if(list$A[k]>list$C[k]) {list$C[k]=list$A[k]}
  
if(list$B[k]<list$D[k]) {list$D[k]=list$B[k]}

}

list

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