【问题标题】:creating an extra column based on two other dataframes基于其他两个数据框创建一个额外的列
【发布时间】:2023-03-22 17:59:02
【问题描述】:

我有三个数据集

一个包含一堆关于风暴的信息。

包含城市全名和缩写的名称。

一个包含每个州的年份和人口。

我想要做的是在第一个名为“人口”的数据帧风暴中添加一列,其中包含使用其他两个数据帧 state_codes 和 states 的每个州每年的人口。

谁能指出我正确的方向?下面是一些示例数据

> head(storms)
  num   yr mo dy     time state magnitude injuries fatalities crop_loss
1   1 1950  1  3 11:00:00    MO         3        3          0         0
2   1 1950  1  3 11:10:00    IL         3        0          0         0
3   2 1950  1  3 11:55:00    IL         3        3          0         0
4   3 1950  1  3 16:00:00    OH         1        1          0         0
5   4 1950  1 13 05:25:00    AR         3        1          1         0
6   5 1950  1 25 19:30:00    MO         2        5          0         0

> head(state_codes)
        Name Abbreviation
1    Alabama           AL
2     Alaska           AK
3    Arizona           AZ
4   Arkansas           AR
5 California           CA
6   Colorado           CO


head(states)
Year Alabama Arizona Arkansas California Colorado Connecticut Delaware
1 1900    1830     124     1314       1490      543         910      185
2 1901    1907     131     1341       1550      581         931      187
3 1902    1935     138     1360       1623      621         952      188
4 1903    1957     144     1384       1702      652         972      190
5 1904    1978     151     1419       1792      659         987      192
6 1905    2012     158     1447       1893      680        1010      194

【问题讨论】:

  • 一般来说,StackOverflow 建议提供一个最小的、可重现的示例 (stackoverflow.com/help/minimal-reproducible-example),在这种情况下,这意味着生成一些任何人都可以运行的假数据,而不是仅仅显示真实的 sn-ps数据。

标签: r dplyr


【解决方案1】:

您没有提供太多数据进行测试,但应该这样做。

首先,将storms 连接到state_codes,这样它的状态名称就在states 中。我们可以同时重命名yr 来匹配states$Year

然后将states 转为长格式。

最后,将新版storms加入到长版states中。

library(dplyr)
library(tidyr)
storms %>%
  left_join(state_codes,by = c("state" = "Abbreviation")) %>%
  rename(Year = yr) -> storms.with.names

states %>%
  pivot_longer(-Year, names_to = "Name",
               values_to = "Population") -> long.states

storms.with.names %>%
  left_join(long.states) -> result

【讨论】:

  • 谢谢,我写了一些与此类似的代码,但我就是做错了。我真的很新,而且自我思考,但再次感谢你让我开心!
  • 我们都是从某个地方开始的。坚持下去!
【解决方案2】:

这个答案不使用 dplyr,但我提供它是因为我知道它在大型数据集上非常快。

它遵循与公认答案相同的第一步:将州名称合并到风暴数据集中。但后来它做了一些聪明的事情(我偷了这个主意):它创建了一个行号和列号矩阵,然后使用它从“状态”数据集中提取新列所需的元素。

#Add the state names to storms
storms<-merge(storms, state_codes, by.x = 6, by.y = 2, all.x = T)

#Get row and column indexes for the elements in 'states'
r<-match(storms$year, states$year)
c<-match(storms$state.y, names(states)) #state.y was the name of the merged column
smat<-cbind(r,c)

#And grab them into a new vector
storms$population<-states[smat]

【讨论】:

    猜你喜欢
    • 2016-09-11
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    相关资源
    最近更新 更多