I am trying to append columns at the end of my data frame to show the quarter IDs during which each customer reached various revenue thresholds, e.g. one column for reaching $50M, another for reaching $75M, another for reaching $100M, and then finally for $150M. However, I noticed that the columns in the middle ($75M and $100M) keep getting overridden by the FOR loops for $150M. What should I add or change to my for loops so that it will not override the previous values?
selected output
df <- read.csv("test.csv", header=TRUE) #load data
### $50M threshold
for (row in 1:nrow(df)) {
for (i in 6:35) { #Start in column 6, which is where quarterly rev begins
if (i <= (ncol(df)-4) & (df[row,i] + df[row,i+1] + df[row,i+2] + df[row,i+3])>=50000000 ){ #Identify qtr during which an advertiser reached $50M P4Q
qtr_index = (i+4) - 6
df[row,46] <-sprintf("%dQ%d", floor(qtr_index / 4) + 2016, (qtr_index %% 4) + 1)
break
} else { df[row,46] <- 'N/A'
}
}
}
### $75M threshold
for (row in 1:nrow(df)) {
for (i in 6:35) { #Start in column 6, which is where quarterly rev begins
if (i <= (ncol(df)-4) & (df[row,i] + df[row,i+1] + df[row,i+2] + df[row,i+3])>=75000000){ #Identify qtr during which an advertiser reached $75M P4Q
df[row,47] <- sprintf("%dQ%d", floor(qtr_index / 4) + 2016, (qtr_index %% 4) + 1)
break
} else { df[row,47] <- 'N/A'
}
}
}
### $100M threshold
for (row in 1:nrow(df)) {
for (i in 6:35) { #Start in column 6, which is where quarterly rev begins
if (i <= (ncol(df)-4) & (df[row,i] + df[row,i+1] + df[row,i+2] + df[row,i+3])>=100000000){ #Identify qtr during which an advertiser reached $50M P4Q
df[row,48] <- sprintf("%dQ%d", floor(qtr_index / 4) + 2016, (qtr_index %% 4) + 1)
break
} else { df[row,48] <- 'N/A'
}
}
}
### $150M threshold
for (row in 1:nrow(df)) {
for (i in 6:35) { #Start in column 6, which is where quarterly rev begins
if (i <= (ncol(df)-4) & (df[row,i] + df[row,i+1] + df[row,i+2] + df[row,i+3])>=150000000 ){ #Identify qtr during which an advertiser reached $50M P4Q
df[row,49] <- sprintf("%dQ%d", floor(qtr_index / 4) + 2016, (qtr_index %% 4) + 1)
break
} else { df[row,49] <- 'N/A'
}
}
}
Carey Chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.