I'm trying to loop over the rows of a DF. While looping over the rows i want to do some changes to some rows, and create a new dataframe containing the new rows.
The dataframe i use looks like can be created with this:
df <- structure(
list(
campaign_name = c(
"Category> fanshop",
"Category> trainingspakken",
"Category> trainingsshirts",
"Category> hoodies",
"Category> broeken",
"Category> voetbalshirts"
),
ad_group = c(
"Pro team X[B]",
"Pro team X[B]",
"Pro team X[B]",
"Pro team X[B]",
"Pro team X[B]",
"Pro team X[B]"
),
category = c(
"fanshop",
"trainingspakken",
"trainingsshirts",
"hoodies",
"broeken",
"voetbalshirts"
),
Final_URL = c(
"https://fanshop/Pro-team-X.html",
"https://fanshop/Pro-team-X/_Trainingspakken",
"https://fanshop/Pro-team-X/_Trainingsshirts",
"https://fanshop/Pro-team-X/_Hoodies_Sweaters",
"https://fanshop/Pro-team-X/_Korte-broeken_Lange-broeken",
"https://fanshop/Pro-team-X/_Voetbalshirts"
),
team_name = c(
"Pro team X",
"Pro team X",
"Pro team X",
"Pro team X",
"Pro team X",
"Pro team X"
),
keyword = c(
"+Pro +team +X +fanshop",
"+Pro +team +X +trainingspakken",
"+Pro +team +X +trainingsshirts",
"+Pro +team +X +hoodies",
"+Pro +team +X +broeken",
"+Pro +team +X +voetbalshirts"
),
Criterion_type = c("Broad", "Broad", "Broad", "Broad", "Broad", "Broad")
),
.Names = c(
"campaign_name",
"ad_group",
"category",
"Final_URL",
"team_name",
"keyword",
"Criterion_type"
),
row.names = c("1", "2", "3", "4", "5", "6"),
class = "data.frame"
)
If i use the function below the rows print nicely and are changed. But as soon as i try to assign it to a data frame, off course it will be overwritten every time the loop runs.
for ( row in 1:nrow(df)) {
temp_row <- df[row,]
if (temp_row$Criterion_type == "Broad") {
temp_row$keyword <- gsub("\\+", "", temp_row$keyword)
temp_row$Criterion_type <- "Negative Exact"
}
print(temp_row)
}
After looking into many questions here and try many of the approaches i still did not manage to get it done properly. Much appreciated!
I expect each row to be modified according to the IF statement above. 1 row would look like this:
campaign_name ad_group category Final_URL team_name keyword Criterion_type
Category> voetbalshirts Pro team X[B] voetbalshirts https://fanshop/Pro-team-X/_Voetbalshirts Pro team X paris saint germain voetbalshirts Negative Exact
Some of the questions I tried already: