【发布时间】:2020-11-02 09:25:28
【问题描述】:
我有一个多年来具有唯一位置 ID (loc_id) 的数据集。但是有些位置的编码不同。请注意,对于 loc_id 1 ,location 在 2017 年被编码为“商场”,但在其余年份被编码为“金融机构”。
data <- tribble(
~year, ~location, ~loc_id,
"2017","mall",1,
"2018","financial institution",1,
"2019","financial institution",1,
"2020","financial institution", 1)
我需要创建两个新变量。第一个变量查看location 列中的任何行是否包含字符串“金融机构”,如果包含,则该变量称为“金融机构”。这个变量是location_clean。
第二个变量查看location变量并检查位置字符串是否有任何差异,如果有差异,我们创建一个“是/否”二进制变量。这个变量叫做location_same。
我附上了一个最终数据集应该是什么样子的示例。
data <- tribble(
~year, ~location, ~loc_id, ~location_clean, ~location_same,
"2015","mall", 1, "financial institution", "no",
"2016","mall", 1, "financial institution", "no",
"2017","mall", 1, "financial institution", "no",
"2018","financial institution", 1, "financial institution", "no",
"2019","financial institution", 1, "financial institution", "no",
"2020","financial institution", 1, "financial institution", "no")
我需要跨loc_id 执行这些步骤,因为实际数据集中有很多位置。
谢谢,
【问题讨论】:
-
如果 loc_id 组中没有“金融机构”,您的 location_clean 必须是什么?
-
哦,好问题。如果“'金融机构”不在 loc_id 中,则 location clean 应该是 location 列中的任何内容,无论它在不同年份中有何不同。
-
是的,我在我的回答中也提到过,你能检查一下这是否适合你吗?
-
我刚刚检查过了。代码的第一部分没有问题,并且 location_clean 变量已正确编码。但是 location_same 变量将所有内容编码为“否”,即使它们没有不同。
-
您现在可以检查一下吗?