在这里可能会被问到很多次,但是由于我的函数返回了数据帧,所以我无法将其与任何内容相关联。
我有自定义函数,该函数构建模型并在一个列中输出带有斜率(coeff2),在另一列中包含intercept(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
现在,我想将函数应用于sample_ids的每个唯一子集,并仅输出一个数据帧,并将一条记录作为每个子集的输出。
dplyr
您可以do
在中使用dplyr
:
library(dplyr)
df %>%
group_by(sample_id) %>%
do(f.get_reg(.))
这使:
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
数据表
使用.SD
在data.table
:
library(data.table)
df <- data.table(df)
df[,f.get_reg(.SD),sample_id]
得到相同的结果:
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
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
这使:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句