R - Horizontal Count of Variables with Values NOT EQUAL to -8

Viewed 22

I wish to create a new variable named "NumberChild" to specify the number of children EACH person has in the R data frame.

My data looks like this:

Person ID Child 1 ID Child 2 ID Child 3 ID Child 4 ID
10011 133088 -8 -8 -8
10012 133088 -8 -8 -8
10013 133077 133066 -8 -8
10014 122099 122089 122079 -8
10015 -8 -8 -8 -8
10016 -8 -8 -8 -8

I wish my new variable "NumberChild" to look like this: ("-8" means this person has no such child)

Person ID Child 1 ID Child 2 ID Child 3 ID Child 4 ID NumberChild
10011 133088 -8 -8 -8 1
10012 133088 -8 -8 -8 1
10013 133077 133066 -8 -8 2
10014 122099 122089 122079 -8 3
10015 -8 -8 -8 -8 0
10016 -8 -8 -8 -8 0

What I tried with the dplyr package:

df_new <- df %>%
  mutate(NumberChild = if_else(Child_1_ID != -8,1,0)) 

I only get the following: (Here, the new variable "NumberChild" only specify whether each person has at least 1 child or 0 child, it's a dummy variable - but I don't want a dummy variable, I want a numerical variable specifying the number of child)

Person ID Child 1 ID Child 2 ID Child 3 ID Child 4 ID NumberChild
10011 133088 -8 -8 -8 1
10012 133088 -8 -8 -8 1
10013 133077 133066 -8 -8 1
10014 122099 122089 122079 -8 1
10015 -8 -8 -8 -8 0
10016 -8 -8 -8 -8 0

Please help, thank you!

1 Answers

You can use rowwise() with c_across here.

df %>% 
   rowwise() %>% 
   mutate(NumberChild=sum(c_across(starts_with("Child"))!=-8))

The rowwise tells dplyr to look at one row at a time, rather than an entire column at a time which is the default. Then when you use c_across it will return a vector of values for the columns you select for each given row. Here we could the number of values not equal to -8 using the sum(val != -8) idiom.

Related