我有以下数据框 (X1),我想从中创建一个新数据框,以仅包含年份和 2010:2050 年的 PopTotal。
如何将这些信息提取到新的 df 中?然后我将使用回归模型对 df 进行预测。
LocID Location year PopMale PopFemale PopTotal PopDensity
277246 900 World 1950 1266260 1270171 2536431 19.497
277247 900 World 1951 1290238 1293797 2584034 19.863
277248 900 World 1952 1313855 1317007 2630862 20.223
277249 900 World 1953 1337453 1340156 2677609 20.582
277250 900 World 1954 1361314 1363533 2724847 20.945
277251 900 World 1955 1385658 1387362 2773020 21.316
我希望输出看起来像这样:
year PopTotal
2010 123
2011 456
... ...
2050 789
答案 0 :(得分:2)
在这里,我们可以subset
和select
df2 <- subset(df1, year %in% 2010:2050, select = c(year, PopTotal))
或者另一个选项是filter
library(dplyr)
df2 <- df1 %>%
select(year, PopTotal) %>%
filter(year %in% 2010:2050)
答案 1 :(得分:1)
使用 data.table
的 between
选项
setDT(df)[between(year, 2010, 2050), .(year, PopTotal)]