识别R中并矢数据中的匹配观测值
见鬼,各位 我正在努力解决以下问题。目前,我有一个如下所示的数据集:识别R中并矢数据中的匹配观测值,r,dataframe,dplyr,data-cleaning,data-transform,R,Dataframe,Dplyr,Data Cleaning,Data Transform,见鬼,各位 我正在努力解决以下问题。目前,我有一个如下所示的数据集: living_in from Year stock Austria Australia 2014 2513 Austria Australia 2013 2000 Germany Austria 2010 6000 Australia Aust
living_in from Year stock
Austria Australia 2014 2513
Austria Australia 2013 2000
Germany Austria 2010 6000
Australia Austria 2014 3000
Austria Australia 1993 NA
现在,我想确定符合以下标准的所有观察结果:
- 应该是同一年的
- 应包含当年相同的国家/地区对
- 不应包含钠
living_in from Year stock dummy
Austria Australia 2014 2513 1
Austria Australia 2013 2000 0
Germany Austria 2010 6000 0
Australia Austria 2014 3000 1
Austria Australia 1993 NA 0
对于每个国家/地区组合,无论其顺序如何(A-B与B-A相同),如果同一
年的行数超过1行且所有股票值均为非NA
或指定0,则将1分配给伪列
library(dplyr)
df %>%
group_by(col1 = pmin(living_in, from), col2 = pmax(living_in, from), Year) %>%
mutate(dummy = as.integer(n() > 1 && all(!is.na(stock)))) %>%
ungroup %>%
select(-col1, -col2)
# living_in from Year stock dummy
# <chr> <chr> <int> <int> <int>
#1 Austria Australia 2014 2513 1
#2 Austria Australia 2013 2000 0
#3 Germany Austria 2010 6000 0
#4 Australia Austria 2014 3000 1
#5 Austria Australia 1993 NA 0
库(dplyr)
df%>%
分组依据(col1=pmin(居住在,从),col2=pmax(居住在,从),年)%>%
mutate(dummy=as.integer(n()>1&&all(!is.na(stock)))%>%
解组%>%
选择(-col1,-col2)
#从一年前开始居住
#
#1奥地利-澳大利亚2014 2513 1
#2奥地利澳大利亚2013 2000 0
#3德国奥地利2010 60000
#4澳大利亚奥地利2014 3000 1
#5奥地利澳大利亚1993 NA 0
数据
df <- structure(list(living_in = c("Austria", "Austria", "Germany",
"Australia", "Austria"), from = c("Australia", "Australia", "Austria",
"Austria", "Australia"), Year = c(2014L, 2013L, 2010L, 2014L,
1993L), stock = c(2513L, 2000L, 6000L, 3000L, NA)),
class = "data.frame", row.names = c(NA, -5L))
df感谢您的澄清@RonakShah。我添加了一个预期的输出。