问题
I'm new to R and trying to create a new row based on values on previous rows.
Sample data:
df <- data.table(Item = c("a", "b", "c", "d"),
"2010FY" = c(3, 5, 2, 2),
"2011FY" = c(5, 6, 2, 1),
"2012FY" = c(-1, 2, 2, 0.5))
I would like to create a new row that divides the 3rd row by the 4th row. Let's call this Item "e" and ideally should like this:
Item 2010FY 2011FY 2012FY
1 a 3 5 -1
2 b 5 6 2
3 c 2 2 2
4 d 2 1 0.5
5 e 1 2 4
Using dplyr, my first attempt is:
df <- bind_rows(df, e = df[Item %in% "c", ] / df[Item %in% "d", ])
This does not work because characters are not divisible (ie. The Item column).
I found that the function mutate_if would work but only by column. Is there a way I can do this by row?
Thank you so much.
回答1:
As pointed out in the comments above, this worked:
rbind(df, c(Item="e", df[df$Item == "c", -1] / df[df$Item == "d", -1]))
来源:https://stackoverflow.com/questions/55013522/r-creating-a-new-row-based-on-previous-rows