【发布时间】:2019-05-06 17:27:48
【问题描述】:
问题:
我有一个如下所示的数据框:
YEAR Region Illness_Code Illness_description COUNT
2014 A ABC test 222
2015 A ABC test 122
2016 A ABC test 111
2014 B XYZ testttt 333
2015 B XYZ testttt 3232
2016 B XYZ testttt 123
2014 C ABC test 333
2015 C ABC test 123
2016 C ABC test 123
.....
我只能得到每个distinct illnesses 的系数,但不能得到每个region 的系数。
下面是使用的代码:
# Get only illnesses which occurs every year
df <- df %>%
group_by(Illness_Code) %>%
filter(n() == 3)
# To dataframe
df <- data.frame(df)
# Loop through the dataframe and apply model
out <- lapply(
unique(df$Illness_Code),
function(c){
sub_cases <- subset(df, Illness_Code == c)
m <- lm(formula = COUNT ~ YEAR, data = sub_cases)
coef(m)
})
# Format the data
out <- do.call(rbind, out)
# Make it a dataframe
out <- data.frame(out)
结果如下:
X.Intercept. YEAR
1 37254.05 -787.33
2 30745.21 3005.84
3 6992.99 2480.82
4 8391.65 3521.96
5 19298.03 -345.88
6 15163.82 -438.50
我想要的是每个region 获得每个distinct illnesses 的coefficients。
问题:
如何按distinct illnesses 和region 对其进行分组?
所以结果应该是:
Region Illness_Code Illness_description Intercept Slope COUNT_2016
A ABC test 222.123 15 111
A XYZ testttt 122.222 121.1 222
B ABC test ... ... ...
B XYZ testttt
C ABC test
C XYZ testttt
.....
【问题讨论】:
-
你可以像这样
split(df1, list(df1$Region,df1$Illness_Code))那样分成两列 -
@A.Suliman 对不起。我不确定你的意思。能详细点吗?
标签: r dplyr linear-regression plyr lm