R: Creating a new row based on previous rows

こ雲淡風輕ζ 提交于 2021-02-10 15:55:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!