如何格式化国家和年份的数据,以便在R中进行回归?

时间:2018-03-11 14:15:58

标签: r regression linear-regression data-cleaning

我有几组数据,有一个解释变量,我想用它来解释其他几个因变量。数据随时间推移,解释变量目前采用以下格式(称之为explain_index)

         1900  1901   ... 2000
Country1  327.1 253.5 ... 537.9
Country2  357.3 300.9 ... 510.7
...       ...   ...   ... ...
Country40 225.7 258.2 ... 451.4 

和因变量的默认格式将采用相同的格式。假设我有一个看似

的因变量(称之为GDP)
         1900  1901   ... 2000
Country1  18   25     ... 93
Country2  20   15     ... 78
...       ...   ...   ... ...
Country40 4    7      ... 85

然后还有几个类似的格式,比如说(market_size)等:

         1900  1901   ... 2000
Country1  7    9      ... 25
Country2  9    11     ... 27
...       ...  ...    ... ...
Country40 0    1      ... 8

我想要做的是分别使用解释变量(解释性索引)对每个变量进行线性回归,得到“整体”线性回归。

基本的 lm(GDP ~ explanatory_index) 只是抛出错误,正如我预期的那样,而且我不想单独或每年分别回归每个国家,因为这个想法是为了表明该指数在不同国家和跨时间具有显着的解释力,并且可以解释某些增长的要素。

我最好尝试将数据转换为更像:

               Explanatory_Index GDP market_size  
Country1_1900  327.1             18  7
Country1_1901  253.5             25  9
...
Country1_2000  537.91            93  25
...            ...               ... ...
Country40_1900 225.7             4   0
Country40_1901 258.2             7   1
...            ...               ... ...
Country40_2000 451.4             85  8

我可以在那里跑 lm(df$GDP, df$explanatory_index)?或者有没有办法用原始数据格式执行此操作?

我理解R的基础知识,但是当谈到结构以及R如何读取内容时,它不符合我对其他语言编程的先入为主的概念。我假设这里有一些lapply版本,但我似乎无法弄明白。如果有更简单的方法,我愿意修改数据格式。

1 个答案:

答案 0 :(得分:0)

最后一个表格最适合lm

您可以执行以下操作。我只做了两张桌子。您可以将所有内容扩展到您拥有的表数量。

library(dplyr)
library(tidyr)

df1 <- df1 %>% gather(year, value = index, -country) %>% 
  unite("country_year", c("country", "year"))

df2 <- df2 %>% gather(year, value = gdp, -country) %>% 
  unite("country_year", c("country", "year"))

# assuming identical number of rows in country_year, otherwise use a different join
total <- inner_join(df1, df2, by ="country_year")

    country_year index gdp
1  Country1_1900 327.1  18
2  Country2_1900 357.3  20
3 Country40_1900 225.7   4
4  Country1_1901 253.5  25
5  Country2_1901 300.9  15
6 Country40_1901 258.2   7
7  Country1_2000 537.9  93
8  Country2_2000 510.7  78
9 Country40_2000 451.4  85

示例数据:

df1 <- structure(list(country = c("Country1", "Country2", "Country40"), 
                      x1900 = c(327.1, 357.3, 225.7), 
                      x1901 = c(253.5, 300.9, 258.2), 
                      x2000 = c(537.9, 510.7, 451.4)), 
                 .Names = c("country", "1900", "1901", "2000"), 
                 class = "data.frame", 
                 row.names = c(NA, -3L))


df2 <- structure(list(country = c("Country1", "Country2", "Country40"), 
                      x1900 = c(18, 20, 4), 
                      x1901 = c(25, 15, 7), 
                      x2000 = c(93, 78, 85)), 
                 .Names = c("country", "1900", "1901", "2000"), 
                 class = "data.frame", 
                 row.names = c(NA, -3L))