I am running R in Rstudio.
I have a data frame that has the following columns: y0, y1, y2, y3, .... yn and yb0, yb1, yb2, yb3... ybn where n could be as large as 1000.
I want to do row sums such that y0=y0+yb0, y1=y1+yb1, y2=y2+yb2...., yn=yn+ybn
So, it is like updating y0, y1, y2.... yn.
I tried using rowwise() with mutate( across ()) but not working. tmpA is my data with the y's and the yb's
tmpB <- tmpA %>%
rowwise() %>%
mutate(
across(starts_with("y"), ~ . + get(paste0("yb", substr(cur_column(), 2))), .names = "yc{substr(cur_column(), 2)}")
) %>%
ungroup()
I don't know if the codes make sense but I've got errors and not sure how to fix it. I want to keep all variables in the original dataset but drop the 'yb's in the output. Thank you in advance.
While it is generally frowned on
forcycles, here it would add to the simplicity and readability of the solution.Since you didn't provide sample data, we don't know if
nis known beforehand or ify1,y2, ..., are necessarily sequential. So I will go with a simple solution and assume they are andnis known. This means that the numbers will go strictly from1tonThe
dfwill be updated in place.