我有一个这样的数据表:
library(tidyverse)
library(lubridate)
library(data.table)
DT <- data.table(
"Date"=rep(seq(ymd('2000-01-01'),ymd('2020-12-01'), by = '1 month'),3),
"Country"=rep(c("France","Germany","Italy"),each=21*12),
"Population"=rep(seq(from=10000,to=(10000+21*12-1)),3))
(是的,我并没有真正受到启发来模拟人口)。
现在我想要一个新变量,例如 population2
,但在 2000 年初缩小到 value = 100,并且特定于每个国家(即使它们在这里相同)。
这样每个值都会有 Population2:=100*Population/Population{for the given country, at date=2000-01-01}
最佳答案
如果日期没有丢失并且是有序的,使用 first
返回 Population 的第一个值,按“Country”分组
DT[, Population2 := 100 * Population/first(Population), by = Country]
或者如果没有排序,我们也可以使用i
根据'Date'做order
DT[order(Date), Population2 := 100 * Population/first(Population), by = Country]
或者也可以使用 ==
DT[, Population2 := if("2000-01-01" %in% Date) {
100 * Population/Population[Date == "2000-01-01"]
} else NA_real_, by = Country]
或者另一种选择是基于“日期”进行子集化后的连接
DT[DT[Date == "2000-01-01"], Population2 := Population/i.Population,
on = .(Country)]
关于r - 如何引用给定行以在基数 100 中创建变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66522790/