根据 R 中的索引值重复将数据集的同一部分与数据集的其他部分进行比较



我有一个数据帧,如下所示:

state  year  value
1      1980  4
1      1981  5
1      1982  4
2      1980  2
2      1981  3
2      1982  4
100    1980  3
100    1981  2
100    1982  5

在实际数据集中,状态比此处显示的要多。我想在 100 州和所有其他州之间进行比较。

具体来说,对于每个州,我想找出该州在特定年份给出的值与同一年为状态 100 给出的值之间的差异。下面,我展示了如何比较状态 1 和状态 100 之间的 1980 年值。

df_1 <- df %>% filter(state == 1) 
df_100 <- df %>% filter(state == 100)
df_1_1980 <- df_1 %>% filter(year == 1980) 
df_100_1980 <- df_100 %>% filter(year == 1980)
difference <- df_1_1980$value - df_100_1980$value

如何对数据帧中的所有其他状态和年份执行此操作?

我考虑过的一种可能性是创建一个仅由状态 100 中的数据组成的数据帧,然后将其连接到原始数据帧,如下所示:

state  year  value  state100  year100  value100
1      1980  4      100       1980     3
1      1981  5      100       1981     2
1      1982  4      100       1982     5
2      1980  2      100       1980     3
2      1981  3      100       1981     2
2      1982  4      100       1982     5

然后,我可以从每行的 df$value100 中减去 df$value。我认为有更好的方法可以做到这一点。

我们可以filter不等于 100 的"状态",left_join"状态"为 100 的数据集,by"年",并得到"值"列之间的差异

library(dplyr)
df %>% 
filter(state != 100) %>% 
left_join(df %>%
filter(state == 100) %>% 
select(-state), by = c('year')) %>% 
transmute(state, year, value = value.x, difference = value.x - value.y)
#  state year value difference
#1     1 1980     4          1
#2     1 1981     5          3
#3     1 1982     4         -1
#4     2 1980     2         -1
#5     2 1981     3          1
#6     2 1982     4         -1

数据

df <- structure(list(state = c(1L, 1L, 1L, 2L, 2L, 2L, 100L, 100L, 
100L), year = c(1980L, 1981L, 1982L, 1980L, 1981L, 1982L, 1980L, 
1981L, 1982L), value = c(4L, 5L, 4L, 2L, 3L, 4L, 3L, 2L, 5L)), 
class = "data.frame", row.names = c(NA, 
-9L))

相关内容

最新更新