编码/求和功能

时间:2019-01-04 14:07:47

标签: r function dplyr sum

我正在创建一个函数,该函数将根据人们的家庭组成对他们进行编码。如下面的代码所示,#21表示一对夫妇有一个或多个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

使用case_when()和between()函数,我标记观察结果,如下所示:

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")

然后,我创建一个函数来按家庭对成年人/儿童进行计数。

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}
}

如上所示:

X1 = less than 15 
x2 = 15 to 18
X3 = 18 to 24 
x4 = greater than 24 

我在对hhcomp函数中的总和进行编码时遇到了麻烦,尤其是对于#12和#13。我不确定将&符号和&或(|)运算符放在何处,以及是否需要括号

编辑:

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()

我想计算每个FamID的X项,并使用mutate将代码作为新变量应用于每个ID。

我在逻辑运算符上遇到问题

0 个答案:

没有答案