我有很多data set
以下内容format
:第一列是type
,发生的subsequent columns
时间不同'type'
。我想每个计算的斜率row (~7000 rows)
为subset T0-T2
,然后t0-t2
输出信息,然后获得平均的斜坡每一行。例如,获取类型1的子集T0-T2和t0-t2的斜率,然后获取行type1的两个值的平均值。有些行完全丢失了数据,而有些行则丢失了一个或两个值。
Type T0 T1 T2 t0 t1 t2
type1 0.2 0.3 0.4 0.3 0.2 0.1
type2 1.4 2.5 3.4 1.5 0.5 3.4
type3 0.4 8.1 8.1 2.2
type4
...
我是的初学者R
,因此尝试这样做一直很困难,就我看来,这似乎很简单。我在缺失值(NA)中遇到错误,对于本网站上类似问题的任何想法或指导,我将不胜感激。谢谢
首先,您可能想编写一个可以计算三个连续值的斜率的函数,如下所示:
slope <- function(x){
if(all(is.na(x)))
# if x is all missing, then lm will throw an error that we want to avoid
return(NA)
else
return(coef(lm(I(1:3)~x))[2])
}
然后可以使用该apply()
函数计算每一行的斜率(MARGIN = 1),如下所示:
df <- read.csv(text =
"Type,T0,T1,T2,t0,t1,t2
type1,0.2,0.3,0.4,0.3,0.2,0.1
type2,1.4,2.5,3.4,1.5,0.5,3.4
type3,0.4,8.1,8.1,,2.2,")
df$slope1 <-
apply(df[,c('T0','T1','T2')],
1,
slope)
df$slope2 <-
apply(df[,c('t0','t1','t2')],
1,
slope)
然后计算平均斜率:
df$average.slope <- (df$slope1 + df$slope2)/2
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句