将自定义函数应用于数据框的每个子集并生成数据帧

ds_*_*ser 3 r plyr tapply dplyr

这里可能会多次询问,但由于我的函数返回数据框,因此我无法将其与任何相关联.

我有自定义函数,它构建模型并在一列中输出斜率(coeff2)的数据帧,在另一列中截取(coeff1),在一列中输入记录的数量等.理想情况下,我在函数中构建自己的数据框并从函数中输出.现在我想基于列对我的输入数据框进行子集化并在其上应用我的函数.

示例: -

f.get_reg <- function(df) {
  linear.model <-lm(df$DM ~ df$FW,)
  N <- length(df$DM)
  slope <- coef(linear.model)[2]
  intercept <- coef(linear.model)[1]
  S <- summary(linear.model)$sigma
  df.out <- data.frame (N,slope, intercept, S)
  return (df.out)
}



sample_id     FW       DM  StdDev_DM Median_DM Count  X90 X60 crit Z.scores
     6724 116.39 16.20690    0.9560414   16.0293    60 3.35 3.2  3.2        1
     6724 116.39 16.20690    0.9560414   16.0293    60 3.35 3.2  3.2        1
     6724 110.24 16.73077    0.9560414   16.0293    60 3.35 3.2  3.2        1
     6728 110.24 16.73077    0.9560414   16.0293    60 3.35 3.2  3.2        1
     6728 112.81 16.15542    0.9560414   16.0293    60 3.35 3.2  3.2        1
     6728 112.81 16.15542    0.9560414   16.0293    60 3.35 3.2  3.2        1
Run Code Online (Sandbox Code Playgroud)

现在我想将我的函数应用于sample_ids的每个唯一子集,并仅输出一个数据帧,其中一个记录作为每个子集的输出.

shr*_*sgm 6

dplyr

您可以使用dodplyr:

library(dplyr)
df %>%
    group_by(sample_id) %>%
    do(f.get_reg(.))
Run Code Online (Sandbox Code Playgroud)

这使:

  sample_id     N       slope intercept            S
      (int) (int)       (dbl)     (dbl)        (dbl)
1      6724     3 -0.08518211  26.12125 7.716050e-15
2      6728     3 -0.22387160  41.41037 5.551115e-17
Run Code Online (Sandbox Code Playgroud)

data.table

使用.SDdata.table:

library(data.table)

df <- data.table(df)
df[,f.get_reg(.SD),sample_id]
Run Code Online (Sandbox Code Playgroud)

这给出了相同的结果:

   sample_id N       slope intercept            S
1:      6724 3 -0.08518211  26.12125 7.716050e-15
2:      6728 3 -0.22387160  41.41037 5.551115e-17
Run Code Online (Sandbox Code Playgroud)

基地R.

使用by:

resultList <- by(df,df$sample_id,f.get_reg)
sample_id <- names(resultList)
result <- do.call(rbind,resultList)
result$sample_id <- sample_id
rownames(result) <- NULL
Run Code Online (Sandbox Code Playgroud)

这使:

  N       slope intercept            S sample_id
1 3 -0.08518211  26.12125 7.716050e-15      6724
2 3 -0.22387160  41.41037 5.551115e-17      6728
Run Code Online (Sandbox Code Playgroud)