r-随着时间的时间填充的数据格式为唯一的键



我确定有一种方法,但是我当然不会在任何地方找到它,或者我不知道如何简单地提出正确的问题来找到一个好的答案,所以我的数据框架具有以下结构...

> head(df)
        city      state  year   population    stat1 stat2 stat3 stat4 stat5
1       BESSEMER     1    1      31509 0.3808436            0 0.63473928   2.8563268    9.5528262
2     BIRMINGHAM     1    1     282081 0.3119671            0 0.97489728   6.0266377    9.1321287
3 MOUNTAIN BROOK     1    1      18221 0.0000000            0 0.05488173   0.2744086    0.4390538
4      FAIRFIELD     1    1      12978 0.1541069            0 0.46232085   3.0050855    9.8628448
5     GARDENDALE     1    1       7828 0.2554931            0 0.00000000   0.7664793    1.2774655
6          LEEDS     1    1       7865 0.2542912            0 0.12714558   1.5257470   13.3502861
  stat6      stat6 stat7 stat8 stat9 cluster
1     26.976419     53.54026  5.712654                    0               0.2856327       9
2     35.670605     65.49183 11.982374                    0               0.4963113       9
3      6.311399     21.40387  1.426925                    0               0.1097635       3
4     21.266759     68.11527 11.480968                    0               1.0787487       9
5      6.770567     23.24987  3.960143                    0               0.0000000       3
6     24.157661     39.79657  4.450095                    0               1.5257470      15
agg
1  99.93970
2 130.08675
3  30.02031
4 115.42611
5  36.28002
6  85.18754

实际上我需要的只是city state yearagg

的4列

我的最终目标是随着时间的推移在数据中发现的每个独特的城市状态对,并与与之相关的agg值。显然,我甚至无法将数据以供GGPLOT识别的格式获取,因此我只需要一些方向,即如何清洁这些数据才能将其介入。我确实在以下代码段中有每个唯一对象的列表。

df_ascending <- df[with(df, order(population)), ]
unique_city_state_pairs_as_df <- unique(as.data.frame(t(apply(df_ascending[,c("city","state")], 1, sort))));

我需要具体的每个唯一的城市状态对...并且我有一个非常垃圾的解决方案,因为我得到了一个单独的数据。帧对象,其中包含df_ascendingunique_city_state_pairs_as_df中每个唯一的城市状态。

出现的潜在问题

  1. 某些城市缺少年数
  2. 有相同名称的城市,但不同的状态
  3. 我最终想在灰度中绘制每个城市的绘制,而在前景中有一个精选的城市,并带有颜色。

我已经为此挣扎了几个星期。我的帽子朝着擅长数据清洁的任何人都戴着,可以将我带到我应该选择的道路上。许多大拇指向所有人提供帮助。

您可以使用dplyr软件包尝试这样的东西

library(dplyr)
df1 <- df %>%
  #this will select relevant columns
  select(city, state, year, agg) %>%
  #this will create a new column with the city and states combined
  mutate(city_state = paste(as.character(city), as.character(state), sep = "_") 
#using na.omit should fix your problem with missing values
ggplot(na.omit(df1), aes(year, agg, color = city_state)+
  geom_point()+
  geom_line()

最新更新