Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add columns to my data frame, including the counts of another columns , for two different column, in R?

I need to count two different columns in a data frame and add the values as two new columns.

In the example below, I want to count x and y

ID  l   x   y
1   s   1   E
1   s   2   NA
1   s   3   E
1   s   4   E
1   s   5   E
2   ss  1   NA
2   ss  2   E
2   ss  3   E
3   m   1   NA
3   m   2   E
3   m   3   NA
3   m   4   NA
3   m   5   E
3   m   6   E
3   m   7   NA
4   mm  1   E
4   mm  2   E

and I need the output to look like the below:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ID  l    n.x    n.y
1   s    5      4
2   ss   3      2
3   m    7      3
4   mm   2      2

How can I use count ()? or other codes?
Thanks

>Solution :

Here is a tidyverse approach. You can group_by your ID column, and count rows that is not NA.

library(tidyverse)

df %>% 
  group_by(ID, l) %>% 
  summarize(n.x = sum(!is.na(x)), n.y = sum(!is.na(y)), .groups = "drop")

# A tibble: 4 x 4
     ID l       n.x   n.y
  <int> <chr> <int> <int>
1     1 s         5     4
2     2 ss        3     2
3     3 m         7     3
4     4 mm        2     2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading