根据数据帧中另一列的条件求和的列

时间:2019-03-28 10:29:30

标签: r dataframe

我有一个数据框,其中包含两列TimeResponse

df = cbind.data.frame(
                     Time = c(1, 1.2, 1.9, 2.2, 2.9, 3.1, 3.2, 3.2, 3.2, 3.6, 3.9, 4, 5.1, 5.99), 
                     Response = c(1, 1, 1, 2, 3, 3, 3, 4, 3.5, 3.6, 3.3, 6, 11, 13)
                     )

我想通过在同一分钟(时间)之内对Response求和来对其进行变换。 [1-2),[2-3),[3-4),[4-5)和[5及以上]。

预期的数据帧将是

dfe = cbind.data.frame(
                      time.range = c(1, 2, 3, 4, 5), 
                      Response = c(3, 5, 19.4, 6, 24)
                      )

2 个答案:

答案 0 :(得分:6)

我们可以使用floor每分钟对其进行分组

library(dplyr)

df %>%
  group_by(minute = floor(Time)) %>%
  summarise(Response = sum(Response))

#   minute Response
#    <dbl>    <dbl>
#1      1      3  
#2      2      5  
#3      3     20.4
#4      4      6  
#5      5     24  

在底数R中使用aggregate

aggregate(Response~floor(Time), df, sum)

还有tapply

tapply(df$Response, floor(df$Time), sum)

为完成data.table选项

library(data.table)
setDT(df)[,sum(Response), by = floor(Time)]

答案 1 :(得分:1)

我们可以使用public class Startup { private readonly IHostingEnvironment _env; private readonly IConfiguration _configuration; public Startup(IConfiguration configuration, IHostingEnvironment env) { _env = env; _configuration = configuration; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonOptions(options => { options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; }); ... 中的rowsum

base R