【问题标题】:r - data formatting into unique keys over time filled by a valuer - 随着时间的推移将数据格式化为唯一键,由值填充
【发布时间】:2017-03-09 22:21:26
【问题描述】:

我确信有一种方法可以做到这一点,但我肯定在任何地方都找不到,或者我不知道如何简洁地提出正确的问题来找到一个好的答案,所以我的数据框具有以下结构。 ..

> 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

我真正需要的是citystateyearagg这4列

我的最终目标是绘制一个随时间推移在数据中找到的每个独特的城邦对以及与之关联的 agg 值的图。我显然什至无法以 ggplot 识别的格式获取数据,所以我只需要一些关于如何清理这些数据以获取数据的指导。我在下面的代码 sn-p 中有一个每个唯一对象的列表。

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_ascending 获得了一个包含unique_city_state_pairs_as_df 中每个独特城市状态的单独data.frame 对象。

可能出现的问题

  1. 有些城市缺少年份
  2. 有城市名称相同,但州不同
  3. 我最终想用灰度绘制每个城市随时间变化的图,在前景中选择带有颜色的城市子集。

我已经为此苦苦挣扎了几个星期。我向任何擅长数据清理并且可以指导我走这条路的人致敬。许多竖起大拇指来帮助大家。

【问题讨论】:

  • 关于 1 和 2,我建议定义 location = paste(city, state, sep="_");使用expand.grid(locations, years) 定义您想要的所有观察结果;将其合并。仅供参考,您应该发布一个可重现的示例并一次问一个问题。见stackoverflow.com/help/how-to-ask

标签: r formatting data-cleaning


【解决方案1】:

您可以使用 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()

【讨论】:

    猜你喜欢
    • 2016-03-27
    • 2021-01-07
    • 2017-07-29
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-24
    • 1970-01-01
    相关资源
    最近更新 更多