首页 > 解决方案 > R:如何使用函数来创建新的数据框?

问题描述

我有一个正在使用的数据集,并尝试使用一个函数将该集中的组的几个描述性统计信息添加到可以导出为 CSV 的数据框中。

这是一个非常简化的数据集(df):

     Well   Time  Value
1    A01    0     3
2    A01    1     4
3    A01    2     5
4    A02    0     2
5    A02    1     3
6    A02    2     4

本质上,我想要做的是为每个组(嗯)提取几个值,例如最小值和最大值,并将它们作为新数据框中的它们自己的行。这是我迄今为止尝试过的函数的一部分代码,但没有成功。我只是添加代码来查找最小值和最大值以简化事情,但我还有大约 15 个其他数据点是我从完整数据集中提取的。

# Dataframe to add to
df1 <- (A, 1, 2)
names(df1) <- c("well", "max", "min") # (plus other values)

# Function
stat.well <- function(x = cont_harmless) {
  
  # Vector of names of wells to loop over
  well <- unique(base$Well)
  
  # Loop to create descriptive statistics
  for (i in seq_along(well)) {
    
    # Subset data to single well
    single_well <- x %>% subset(Well == well[i])
    
    # Maximum Value
    a <- max(single_well$TEER)
    b <- which.max(single_well$TEER)
    
    # Minimum Value
    c <- min(single_well$TEER)
    d <- which.min(single_well$TEER)

    # More code for other values
    # More code for other values
    # More code for other values
    # More code for other values
    
    # Add to df1
    df1 %>% add_row(Well = well[i], max = a, min = c)
  }
  Return(df1)
}
   
stat.well()

当我运行这段代码时,我得到的唯一返回是函数之前的数据框(这是我计划取出的一行)。我确信这不是最优雅的解决方案,但我感谢任何帮助 - 谢谢!

标签: rdataframefunction

解决方案


这是一个dplyr(我认为)可以达到您想要的结果的解决方案。它首先按“Well”列分组,然后计算“Time”和“Value”列的汇总统计数据(最小值和最大值)

library("dplyr")
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

df <- structure(
  list(
    Well = c("A01", "A01", "A01", "A02", "A02", "A02"),
    Time = c(0, 1, 2, 0, 1, 2),
    Value = c(3, 4, 5, 2, 3, 4)
  ),
  row.names = c(NA,-6L),
  class = c("tbl_df", "tbl", "data.frame")
)

df %>%
  group_by(Well) %>%
  summarise(across(c(Time, Value), list(min = min, max = max)))
#> # A tibble: 2 × 5
#>   Well  Time_min Time_max Value_min Value_max
#>   <chr>    <dbl>    <dbl>     <dbl>     <dbl>
#> 1 A01          0        2         3         5
#> 2 A02          0        2         2         4

reprex 包于 2021-10-28 创建(v2.0.1)


推荐阅读