简体   繁体   中英

R mutate new row using dplyr

I have the following data:

library(tidyverse)

d1 <- data_frame('Type' = "all types",
             `1991` = c(1200),
             `1992` = c(4000),
             `1993` = c(6000),
             `1994` = c(8000))

I would like to create a new row which is a calculation of each year. the calculation is the value -10%. So the data would look like this

d2 <- data_frame('Type' = "all types", "summary",
             `1991` = c(1200, 1080),
             `1992` = c(4000, 3600),
             `1993` = c(6000, 5400),
             `1994` = c(8000, 7200))

Now there is a new row, which is the value minus 10%. If the data was in another shape I could do this easily using mutate. However I would like to keep the short format.

Thanks

library(tidyverse)

d1 <- data_frame('Type' = "all types",
                 `1991` = c(1200),
                 `1992` = c(4000),
                 `1993` = c(6000),
                 `1994` = c(8000))

d1 %>%
  mutate_if(is.numeric, ~.*0.9) %>%
  rbind(d1) %>%
  mutate(summary = "summary")

# # A tibble: 2 x 6
#   Type      `1991` `1992` `1993` `1994` summary
#   <chr>      <dbl>  <dbl>  <dbl>  <dbl> <chr>  
# 1 all types   1080   3600   5400   7200 summary
# 2 all types   1200   4000   6000   8000 summary

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM