Carry Over Data Without Using for Loop

How to make variable values carry over outside of if statement

As your code is written, each time the while loop runs, it resets ties, wins, and losses back to zero. Move those expressions outside the while loop, and the values won't be reset with each new game.

Filling in values without a loop

We could use base R to do this. We get the logical index of non-NA 'AAPL' elements ('i1'), cumsum the 'i1' to convert to numeric index, use that to replace the NA elements with non-NA elements.

i1 <- !is.na(z$AAPL)
z$AAPL <- z$AAPL[i1][cumsum(i1)]
head(z)
# Date AAPL
#1 2015-05-31 100
#2 2015-06-01 100
#3 2015-06-02 100
#4 2015-06-03 100
#5 2015-06-04 100
#6 2015-06-05 100
tail(z)
# Date AAPL
#57 2015-07-26 200
#58 2015-07-27 200
#59 2015-07-28 200
#60 2015-07-29 200
#61 2015-07-30 200
#62 2015-07-31 150

PHP: How to carry over data to another page after mysql read using while loop

Just append the ID of the item to your link and then you can get it from the next page as a $_GET variable:

while($row = mysql_fetch_array($result)){
echo '<div class="thumb">';
echo '<a href="template.php?id='.$row['id'].'"><img src='.$row['dresses_pic'].'/></a>';
echo '<p>'.$row['price_'].'</p>';
echo '</div>';
}

template.php

$id = (int) $_GET['id']; // Use this to get the item from the DB

Variable defined inside of function carries over when function is called multiple times

Python creates a function's default parameters once when the code is first compiled and uses that object whenever a default is needed. One consequence is that if the parameter is mutable, like a list, any changes to it are seen in all future calls. One solution is to use a different value as a default and use it to create the default dynamically

def function(var1, var2=None):
if var2 is None:
var2 = [[], 0]
# some code that changes both var1 and var2
return (var2, var1)

Another option is to stop mutating the list in place, but return a copy instead.

from copy import deepcopy

def function(var1, var2=[[], 0]):
var1 = deepcopy(var1)
var2 = deepcopy(var2)
# some code that changes both var1 and var2
return (var2, var1)

How to update each column based on previous column using for loop

A very simple approach is to eliminate the inner loop and vectorize the inner replacement loop. This is not the best solution but closer to what you are more familiar with:

id <- c(101, 102, 103, 104)
visit.1 <- c(0, 21, 0, 21)
visit.2 <- c(0, 0, 50, 0)
visit.3 <- c(0, 0, 0, 44)
visit.4 <- c(NA, NA, 0, 0)
dat <- data.frame(id, visit.1, visit.2, visit.3, visit.4)

for (index in 3:5){
dat[[index]]<-ifelse(dat[[index]]==0, dat[[index-1]], dat[[index]])
}

I am using the for loop to move from column to column. Then the ifelse is looking at the entire column. For the rows that ==0 use the value to the left, if not use the current value.



Related Topics



Leave a reply



Submit