我有一个简单的特征 panel 数据,其中包含 24 年来墨西哥 32 个州的谋杀案。我想创建一个索引,以我数据中的第一年(1994 年)为基础。为此,我正在运行以下代码:
#Taking the data of murders in 1994 from each state and then paste it for all the years
mexico.sf$murders1994 <- mexico.sf$murders[mexico.sf$year==1994]
#Use the murders from each year divided by the murders in 1994 per state to create an index
mexico.sf$murdersrelativeto1994 <- (mexico.sf$murders / mexico.sf$murders1994)
然而,当我运行第一个代码时,出现以下错误:
Error: Assigned data `mexico.sf$murders[mexico.sf$year == 1994]` must be compatible with existing data.
x Existing data has 800 rows.
x Assigned data has 32 rows.
i Only vectors of size 1 are recycled.
Run `rlang::last_error()` to see where the error occurred.
我很清楚,它只需要 32 个 values 因为我每年都在过滤,但是,如何在所有样本中复制这 32 个数据?
回答1
如果不查看实际数据,我不确定我是否正确理解了您的目的。但是如果你只需要用 32 values 覆盖 800 values,也许这样:
mexico.sf$murders1994 <- rep(mexico.sf$murders[mexico.sf$year==1994], 800/32)