R语言 按组在一个框架上运行一个自定义函数

41zrol4v  于 11个月前  发布在  其他
关注(0)|答案(6)|浏览(87)

自定义函数,用于循环遍历嵌套框架中的组。
以下是一些样本数据:

set.seed(42)
tm <- as.numeric(c("1", "2", "3", "3", "2", "1", "2", "3", "1", "1"))
d <- as.numeric(sample(0:2, size = 10, replace = TRUE))
t <- as.numeric(sample(0:2, size = 10, replace = TRUE))
h <- as.numeric(sample(0:2, size = 10, replace = TRUE))

df <- as.data.frame(cbind(tm, d, t, h))
df$p <- rowSums(df[2:4])

字符串
我创建了一个自定义函数来计算值w:

calc <- function(x) {
  data <- x
  w <- (1.27*sum(data$d) + 1.62*sum(data$t) + 2.10*sum(data$h)) / sum(data$p)
  w
  }


当我在整个数据集上运行该函数时,我得到以下答案:

calc(df)
[1]1.664474


理想情况下,我希望返回按tm分组的结果,例如:

tm     w
1    result of calc
2    result of calc
3    result of calc


到目前为止,我已经尝试在我的函数中使用aggregate,但我得到了以下错误:

aggregate(df, by = list(tm), FUN = calc)
Error in data$d : $ operator is invalid for atomic vectors


我觉得我已经盯着这个太久了,有一个明显的答案。

92dk7w1h

92dk7w1h1#

你可以试试split

sapply(split(df, tm), calc)

#       1        2        3 
#1.665882 1.504545 1.838000

字符串
如果你想要一个列表lapply(split(df, tm), calc)
data.table

library(data.table)

setDT(df)[,calc(.SD),tm]
#   tm       V1
#1:  1 1.665882
#2:  2 1.504545
#3:  3 1.838000

j2cgzkjk

j2cgzkjk2#

使用dplyr

library(dplyr)
df %>% 
   group_by(tm) %>%
   do(data.frame(val=calc(.)))
#  tm      val
#1  1 1.665882
#2  2 1.504545
#3  3 1.838000

字符串
如果我们稍微修改函数以包含多个参数,这也可以用于summarise

calc1 <- function(d1, t1, h1, p1){
      (1.27*sum(d1) + 1.62*sum(t1) + 2.10*sum(h1) )/sum(p1) }
 df %>%
     group_by(tm) %>% 
     summarise(val=calc1(d, t, h, p))
 #  tm      val
 #1  1 1.665882
 #2  2 1.504545
 #3  3 1.838000

zbwhf8kr

zbwhf8kr3#

从 * dqr 0.8* 开始,您可以使用group_map

library(dplyr)
df %>% group_by(tm) %>% group_map(~tibble(w=calc(.)))
#> # A tibble: 3 x 2
#> # Groups:   tm [3]
#>      tm     w
#>   <dbl> <dbl>
#> 1     1  1.67
#> 2     2  1.50
#> 3     3  1.84

字符串

nlejzf6q

nlejzf6q4#

library(plyr)
ddply(df, .(tm), calc)

字符串

yshpjwxd

yshpjwxd5#

.和Map功能解决方案.

library(purrr)
df %>% 
    split(.$tm) %>% 
    map_dbl(calc)
# 1        2        3 
# 1.665882 1.504545 1.838000

字符串

ou6hu8tu

ou6hu8tu6#

这是一个整洁的解决方案,也与整洁的格式完全兼容,这里用一个使用palmerpenguins数据集和线性回归模型的例子来说明:

palmerpenguins::penguins |> 
  drop_na() |> 
  group_by(species) |> 
  nest() |> 
  mutate(
    test_results = map(
      .x = data,
      .f = ~ lm(body_mass_g ~ flipper_length_mm, data = .x
      )
      |> broom::tidy(conf.int = TRUE)
    )
  ) |> 
  unnest(test_results) |> 
  select(species, term, estimate, p.value, conf.low, conf.high) |> 
  filter(term != "(Intercept)") |> 
  ungroup()

字符串

相关问题