簡體   English   中英

將選定的行求和到R中的新行

[英]Sum selected rows to a new row in R

我必須在數據框中添加新行total ,以嘗試添加該行的值,該行的值類似於Mazda以下是我正在使用的df。

df <- data.frame(month = c("mazda 3", "mazda cx5", "mazda 6","mazda miata","honda civic","honda accord"),
             april = c(.1,.2,.3,.3,.4,.5),
             may = c(.3,.4,.5,.2,.1,.5),
             june = c(.2,.1,.5,.1,.2,.3))


d2<- df %>% mutate(total == (rowsum(df[-1], df[rownames(month) %like% "Mazda"])))

輸出應為:

df_out <- data.frame(month = c("mazda 3", "mazda cx5", "mazda 6","mazda miata","honda civic","honda accord","total_mazda"),
                 april = c(.1,.2,.3,.3,.4,.5,.8),
                 may = c(.3,.4,.5,.2,.1,.5,1.4),
                 june = c(.2,.1,.5,.1,.2,.3,.9))

我們可以在summarise_at獲取數字列的sum ,同時基於“ month”中的“ mazda”子字符串設置值,創建“ month”列並與原始數據集綁定

library(tidyverse)
df %>% 
  summarise_at(2:4, funs(sum(.[str_detect(month, 'mazda')]))) %>% 
  mutate(month = 'Total') %>% 
  bind_rows(df, .)

嘗試使用apply(df, 2, ...)在第一列中使用grepl掩碼在列之間循環。

我使用了一些bind_(rows|cols)來獲取正確格式的數據幀。

library(dplyr)

df <- data_frame(month = c("mazda 3", "mazda cx5", "mazda 6","mazda miata","honda civic","honda accord"),
             april = c(.1,.2,.3,.3,.4,.5),
             may = c(.3,.4,.5,.2,.1,.5),
             june = c(.2,.1,.5,.1,.2,.3))

df_out <- bind_rows(
  df %>% as_data_frame(),
  data_frame(month = "total_mazda") %>%
    bind_cols(
      apply(df[, 2:ncol(df)],
        2,
        function(x, y = grepl(".*(m|M)azda.*", df[[1]])) sum(x[y])
      ) %>%
        as.list() %>%
        as_data_frame()))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM