[英]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.