How can I sum across rows in data frame and end with a numeric value, even if some values are NA?

48 Views Asked by At

I am attempting to sum the values of columns row-wise, to create a new column with the new values (sum values). Some of the values in the columns are NA, but I'd still like the new column to have a numeric value that represents the other column's values being summed together, row-wise. Does this make sense? I have yet to find any answers and I've tried several codes. I'm a total beginner. Here is what I currently have.

minute_totals <- minute_totals %>% rowwise() %>% 
  mutate(Days_Minutes_Total = sum(TotalActiveMinutes + SedentaryMinutes + TotalTimeInBed, na.rm = TRUE)) %>% 
  relocate(Days_Minutes_Total, .after = TotalTimeInBed)

Now the new dataframe that populates has a column, in the right location, but for every row that was summed with a NA value somewhere, a 0 populates that value box. I am summing up 3 columns, 2 of which always have numeric values, so at the end, there should always be a numeric value. I also tried:

minute_totals <- minute_totals %>% rowwise() %>% 
  mutate(Days_Minutes_Total = sum(c_across(TotalActiveMinutes:TotalTimeInBed))) %>% 
  relocate(Days_Minutes_Total, .after = TotalTimeInBed)

This populated a sum of NA in my Days_Minutes_Total column, again, even though there were two other columns with numeric values.

I'm not sure how to post the dataframe here, I will try to copy the code to populate that.

head(minute_totals)

It looks like this:

    Id TotalActiveMinu… SedentaryMinutes TotalTimeInBed Days_Minutes_To…
       <dbl>            <dbl>            <dbl>          <dbl>            <dbl>
1 1503960366              366              728            346             1440
2 1503960366              257              776            407             1440
3 1503960366              222             1218             NA                0
4 1503960366              272              726            442             1440
5 1503960366              267              773            367             1407
6 1503960366              222              539            712             1473

Trying to get rid of the 0 and make it 1440, as that is the sum of the first two columns I'm summing up. Thanks for any pointers and tips, greatly appreciated.

0

There are 0 best solutions below