R-一个数据帧中的几个线性回归与因子和NA

时间:2016-09-12 10:47:02

标签: r dataframe linear-regression na

我是R的新手,我必须处理超过100列的数据集,简化如下:

Station time data1         data2        data3         data4.....
1       0.0  35.02430310   44.2229390   NA
1       0.8  -68.75294241  -85.5847503  NA
1       1.8  -43.10200333  -62.8035400  NA
3       0.0  0.02217693    0.1336396    0.03203031
3       0.9  7.84203118    -6.4854953   6.22910506
3       2.2  -0.41682970   -7.7022785   0.92807170
17      0.0  4.24864888    4.2104517    0.00000000
17      0.9  1.79933934    -6.6360999   -10.10756894
17      2.1  1.99226283    2.2676248    -13.15887674

对于每个data列,我想用time进行线性回归,但我需要每个站点的系数(这些是因子)。从我使用的plyr包中

ddply(dataframe, .(Station), function(z) coef(lm(data1 ~ time, data=z))) 

例如data1

 Station (Intercept)        t.h.
1  1    9.674588 -40.5399850
2 37    3.130705  -0.6284611
3 48    3.657316  -0.9474062

这是我需要系数的方式,但对于每个data列。现在,即使我将每个data列使用此代码,我也会遇到具有NA值的列的问题。我想简单地删除这些工作站,但仅限于特定列(在这种情况下仅适用于data3。对于data1data2,我希望保留第1站。

有解决方案吗?任何建议都将不胜感激。

数据dput

structure(list(Station = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 
3L, 3L, 3L), .Label = c("1", "3", "17"), class = "factor"), time = c(0, 
0.8, 1.8, 0, 0.9, 2.2, 0, 0.9, 2.2), data1 = c(35.0243031, -68.75294241, 
-43.10200333, 0.02217693, 7.84203118, -0.4168297, 4.24864888, 
1.79933934, 1.99226283), data2 = c(44.222939, -85.5847503, -62.80354, 
0.1336396, -6.4854953, -7.7022785, 4.2104517, -6.6360999, 2.2676248
), data3 = c(NA, NA, NA, 0.1410939, 30.0332505, 11.449285, 0.1161954, 
-2.061781, 0.2289149)), .Names = c("Station", "time", "data1", 
"data2", "data3"), row.names = c(NA, -9L), class = "data.frame")

2 个答案:

答案 0 :(得分:3)

我们需要先将您的data.frame重新设置为长格式,然后省略NA个值,然后根据唯一键('data'Station)应用模型,并且最后整理lm()电话的输出。

library(tidyr)
library(broom)

df %>% gather(data, value, -c(Station, time)) %>%
  na.omit() %>%
  group_by(data, Station) %>% 
  do(tidy(coef(lm(value ~ time, data = .)))) %>%
  spread(names, x) 

#   data Station `(Intercept)`        time
#* <chr>  <fctr>         <dbl>       <dbl>
#1 data1       1     9.5534021 -40.5734035
#2 data1       3     3.1391280  -0.6354857
#3 data1      17     3.6539549  -0.9424560
#4 data2       1    13.8883780 -56.0886482
#5 data2       3    -1.1964287  -3.3757574
#6 data2      17     0.2938263  -0.3353234
#7 data3       3     9.9859146   3.7631889
#8 data3      17    -0.7504115   0.1724399

使用的示例数据是您与列data3共享的内容。

答案 1 :(得分:0)

使用ColumnC会导致第1站完全掉线,这就是你想要的

complete.cases