我正在尝试从现有的数据集创建一个新的数据集。新数据集应该组合原始数据集中的60行,以便将每秒发生的事件总和转换为按分钟计算的总和。列数通常不会预先知道。
例如,对于这个数据集,如果我们将它分成3行一组:
d1
a b c d
1 1 1 0 1
2 0 1 0 1
3 0 1 0 0
4 0 0 1 0
5 0 0 1 0
6 1 0 0 0
我们会得到这个data.frame的。行1包含d1
的行1-3的列和,行2包含d1
的行4-6的列和
d2
a b c d
1 1 3 0 2
2 1 0 2 0
我已经尝试过d2<-colSums(d1[seq(1,NROW(d1),3),])
,它几乎是我能得到的最接近的了。
我还考虑了How to sum rows based on multiple conditions - R?、How to select every xth row from table、Remove last N rows in data frame with the arbitrary number of rows、sum two columns in R和Merging multiple rows into single row的推荐。我已经没有主意了。任何帮助都将不胜感激。
发布于 2018-09-13 06:46:25
创建一个分组变量,对该变量执行group_by
操作,然后单击summarise_all
。
# your data
d <- data.frame(a = c(1,0,0,0,0,1),
b = c(1,1,1,0,0,0),
c = c(0,0,0,1,1,1),
d = c(1,1,0,0,0,0))
# create the grouping variable
d$group <- rep(c("A","B"), each = 3)
# apply the mean to all columns
library(dplyr)
d %>%
group_by(group) %>%
summarise_all(funs(sum))
返回:
# A tibble: 2 x 5
group a b c d
<chr> <dbl> <dbl> <dbl> <dbl>
1 A 1 3 0 2
2 B 1 0 3 0
发布于 2018-09-13 06:39:33
概述
在阅读了Split up a dataframe by number of rows之后,我意识到你唯一需要知道的就是你对split()
d1
的喜好。
在本例中,您希望将d1
拆分为基于每3行的多个数据帧。在本例中,使用rep()
指定希望序列中的每个元素- 1:2
-重复三次(行数除以序列的长度)。
在此之后,逻辑包括使用map()
对d1 %>% split()
之后创建的每个数据帧的每一列求和。在这里,summarize_all()
很有用,因为您不需要提前知道列名。
计算完成后,使用bind_rows()
将所有观测值堆叠回一个数据帧中。
# load necessary package ----
library(tidyverse)
# load necessary data ----
df1 <-
read.table(text = "a b c d
1 1 0 1
0 1 0 1
0 1 0 0
0 0 1 0
0 0 1 0
1 0 0 0", header = TRUE)
# perform operations --------
df2 <-
df1 %>%
# split df1 into two data frames
# based on three consecutive rows
split(f = rep(1:2, each = nrow(.) / length(1:2))) %>%
# for each data frame, apply the sum() function to all the columns
map(.f = ~ .x %>% summarize_all(.funs = funs(sum))) %>%
# collapse data frames together
bind_rows()
# view results -----
df2
# a b c d
# 1 1 3 0 2
# 2 1 0 2 0
# end of script #
https://stackoverflow.com/questions/52304224
复制相似问题