如何汇总数据并将新行绑定到现有数据框?

问题描述 投票:0回答:1

编辑给予

reprex
回应评论。

我正在阅读加州 58 个县几年来的公共气温数据。我想创建一个摘要,即全州范围内的每日平均值,然后 将这些平均值放入数据框顶部的新行中,并通过单个管道步骤将县数据放入其中。

我现在分三个步骤执行此操作:(1) 读取县数据,(2) 单独创建平均值,以及 (3) 将新创建的平均值划船绑定到数据。

这是一个代表:

#### Reprex ####
library(tidyverse)

df1 <-
  data.frame(
    name = toupper(c(rep(letters[1:5], each=5))),
    x = as.character(c(rnorm(25, 55, 10)))
  )

df2 <- df1 |>
  group_by(name) |>
  mutate(x = mean(as.numeric(x), narm = TRUE)) |> 
  ungroup() |> 
  select(name, x) |>
  unique() |>
  mutate(name = "Z")
  
df <- rbind(df1, df2) 

这是我到目前为止所尝试过的,但没有成功。两者都会抛出错误消息:

Error in UseMethod("summarise") :  no applicable method for 'summarise' applied to an object of class "c('double', 'numeric')"

#Test 1
df <- 
  data.frame(
    name = toupper(c(rep(letters[1:5], each=5))),
    x = as.character(c(rnorm(25, 55, 10)))
  ) |> 
  group_by(name) |> 
  select(name, x) |>
  do(bind_rows(., data.frame(name = "Z", 
                             mutate(x = mean(as.numeric(.$x), narm = TRUE))))) |>
  ungroup()
  
#Test 2
df <- 
  df <- 
  data.frame(
    name = toupper(c(rep(letters[1:5], each=5))),
    x = as.character(c(rnorm(25, 55, 10)))
  ) |> 
  group_by(name) |> 
  select(name, x) |>
  do(bind_rows(., data.frame(name = "Z", 
                             mutate(x = summarize(mean(as.numeric(.$x), narm = TRUE)))))) |>
  ungroup()

非常感谢任何帮助。

r dplyr pipe bind-rows
1个回答
0
投票

基本的 R 管道不允许您多次使用它正在管道的对象 - 这里需要两次,一次附加到,一次获取手段 - 但你可以通过管道到匿名函数来解决这个问题, 像这样。 (请注意,我将数据大小减少到 3 组,每组 3 个,以便更容易查看和设置种子,以便随机数生成完全可重现。)

library(dplyr)
set.seed(47)
df <- 
  data.frame(
    name = toupper(c(rep(letters[1:3], each=3))),
    x = as.character(c(rnorm(9, 55, 10)))
  ) |>
  mutate(x = as.numeric(x)) |>
  (
    \(dd) bind_rows(dd, summarize(dd, x = mean(x), .by = name))
  )()
df
#    name        x
# 1     A 74.94696
# 2     A 62.11143
# 3     A 56.85405
# 4     B 52.18235
# 5     B 56.08776
# 6     B 44.14263
# 7     C 45.14518
# 8     C 55.15131
# 9     C 52.47954
# 10    A 64.63748
# 11    B 50.80424
# 12    C 50.92534

我不太喜欢这样,从风格上讲,我会分两步进行,1 读取和清理数据,2 计算和追加。基本 R 管道的占位符

_
需要一个命名参数,而
bind_rows
没有,所以我们仍然需要一个匿名函数,但我仍然更喜欢这种方式:

## step 1
df <- 
  data.frame(
    name = toupper(c(rep(letters[1:3], each=3))),
    x = as.character(c(rnorm(9, 55, 10)))
  ) |>
  mutate(x = as.numeric(x))
 
## step 2
df = df |>
  summarize(x = mean(x), .by = name) |> 
  (\(x) bind_rows(df, x))()

如果您不介意

magrittr
管道,您可以将步骤2简化为:

## alternate step 2
df = df |>
  summarize(x = mean(x), .by = name) %>%
  bind_rows(df, .)
© www.soinside.com 2019 - 2024. All rights reserved.