![](/img/trans.png)
[英]How can I create a function to generate new variables based on values in different dataframe in R
[英]R: How can I use a function to create a new dataframe?
我有一個正在使用的數據集,並嘗試使用一個函數將該集中的組的幾個描述性統計信息添加到我可以導出為 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()
當我運行這段代碼時,我得到的唯一返回是函數之前的數據框(這是我計划取出的一行)。 我確定這不是最優雅的解決方案,但我感謝任何幫助 - 謝謝!
這是一個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 包(v2.0.1) 於 2021 年 10 月 28 日創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.