I am creating a function which will code people based on their family composition. As seen in the code below, #21 indicates a couple with with one or more children aged below 15.
# 10 One adult without children
# 11 One adult with at least an own son or daughter aged less than 15
# 12 else: an own child aged 15 to 24 (1)
# 13 else: another child aged less than 15
# 20 One couple without children
# 21 One couple with at least:an own son or daughter aged less than 15
# 22 else: an own child aged 15 to 24 (1)
# 23 else: another child aged less than 15
Using the case_when() and between() functions I label observations as shown below:
V(x)$age.code <- case_when(V(x)$age <= 15 ~ "x1",
between(V(x)$age, 15, 18) ~ "x2",
between(V(x)$age, 18, 24) ~ "X3",
V(x)$age > 24 ~ "X4")
I then create the function to count adults/children by household.
hhcomp <- function(x){
if (sum(x == "X4", na.rm = T) == 1 | sum(x == "x3", na.rm = T) == 1)
{y <- "10"}
else if (sum(x == "X4", na.rm = T) | sum(x == "X3", na.rm = T) == 1 &
sum(x == "X1", na.rm = T) >= 1)
{y <- "11"}
else if ((sum(x == "X4", na.rm = T) | sum(x == "X3", na.rm = T) == 1) &
sum(x == "X2", na.rm = T) >= 1 & sum(x == "X1") >= 1)
{y <- "12"}
else {y <- NA}
}
As seen above:
X1 = less than 15
x2 = 15 to 18
X3 = 18 to 24
x4 = greater than 24
I am having trouble coding the sums in the hhcomp function, especially for #12 and #13. I am unsure of where to put the ampersand (&) and or (|) operators and if brackets are required
EDIT:
ID FamID Age.Code
1 A1 X1
2 A1 X3
3 A2 X4
4 A2 x4
df.2 <- df %>% group_by(FamID) %>% mutate(code = hhcomp(Age.Code)) %>%
ungroup()
I want to count the X terms for each FamID and apply the code to each ID as a new variable using mutate.
I am having problems with the logical operators