我有关于1990-1999年间已婚并有时改姓的妇女的数据。但是,我并不总是知道确切的名称更改年份,只是我的姓氏在x年和y年之间有所更改。在原始数据中,仅将旧姓氏划掉,并在其旁边写上新姓氏,这在“ crossed_over”列中表示。例如,莎拉·史密斯(Sarah Smith)在1994-1999年的某个时候将她的名字改成了莎拉·德雷珀(Sarah Draper)。
我想要的是每个女人每年都有一个唯一的姓氏,例如Liza Moore,她的名字改为Liza Neville,最好在分配姓氏时使用“ crossed_over”列取平均值。例如,莎拉·史密斯(Sarah Smith)在1997年成为莎拉·德雷珀(Sarah Draper),玛丽·金(Mary King)在1997或1998年成为玛丽·费舍尔(Mary Fisher)。
有人对我如何使用下面的示例实现此建议吗?
library(tidyverse)
id <- rep(1:4, each = 10)
year <- rep(1990:1999, 4)
first_name <- c(rep("molly", 10), rep("sarah", 10), rep("mary", 10), rep("liza", 10))
last_name <- c(rep("johnson", 10), rep("smith", 4), rep("smith draper", 6), rep("king", 5), rep("king fisher", 5),
rep("moore", 7), rep("neville", 3))
crossed_over <- c(rep(NA, 10), rep(NA, 4), rep("smith", 6), rep(NA, 5), rep("king", 5), rep(NA, 10))
df <- tibble(id, year, first_name, last_name, crossed_over)
这是一种方法。对于这些行crossed_over
的名称,设置new_last_name
到crossed_over
的行上半年的名字,以及之间的区别crossed_over
,并last_name
为行下半年。
library(tidyverse)
library(stringr)
df %>%
filter(!is.na(crossed_over)) %>%
group_by(across(c(-year))) %>%
mutate(new_last_name = ifelse(row_number() <= n()/2,
crossed_over,
str_trim(str_remove(last_name, crossed_over)))) %>%
ungroup() %>%
right_join(df) %>%
mutate(new_last_name = coalesce(new_last_name, last_name)) %>%
arrange(id, year)
输出量
id year first_name last_name crossed_over new_last_name
<int> <int> <chr> <chr> <chr> <chr>
1 1 1990 molly johnson NA johnson
2 1 1991 molly johnson NA johnson
3 1 1992 molly johnson NA johnson
4 1 1993 molly johnson NA johnson
5 1 1994 molly johnson NA johnson
6 1 1995 molly johnson NA johnson
7 1 1996 molly johnson NA johnson
8 1 1997 molly johnson NA johnson
9 1 1998 molly johnson NA johnson
10 1 1999 molly johnson NA johnson
11 2 1990 sarah smith NA smith
12 2 1991 sarah smith NA smith
13 2 1992 sarah smith NA smith
14 2 1993 sarah smith NA smith
15 2 1994 sarah smith draper smith smith
16 2 1995 sarah smith draper smith smith
17 2 1996 sarah smith draper smith smith
18 2 1997 sarah smith draper smith draper
19 2 1998 sarah smith draper smith draper
20 2 1999 sarah smith draper smith draper
21 3 1990 mary king NA king
22 3 1991 mary king NA king
23 3 1992 mary king NA king
24 3 1993 mary king NA king
25 3 1994 mary king NA king
26 3 1995 mary king fisher king king
27 3 1996 mary king fisher king king
28 3 1997 mary king fisher king fisher
29 3 1998 mary king fisher king fisher
30 3 1999 mary king fisher king fisher
31 4 1990 liza moore NA moore
32 4 1991 liza moore NA moore
33 4 1992 liza moore NA moore
34 4 1993 liza moore NA moore
35 4 1994 liza moore NA moore
36 4 1995 liza moore NA moore
37 4 1996 liza moore NA moore
38 4 1997 liza neville NA neville
39 4 1998 liza neville NA neville
40 4 1999 liza neville NA neville
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句