0

Toy data:

dat <- structure(list(
  country = c("USA", "USA", "Japan", "Japan", "Japan"),
  values = c(25, 30, 20, 45, 31)),
  class = "data.frame",
  row.names = c(NA, -5L))

I want to add a column 'N', which contains the number of observations per country.

Desired output:

#  country values  N
1     USA     25   2
2     USA     30   2
3   Japan     20   3
4   Japan     45   3
5   Japan     31   3

I have found similar questions here and here. But I do not want to create a summary and/or pivot the data as in these questions.

I only want to add a column with the number of observations. I guess this is extremely easy, but I cannot make it work!

Please note, I need to use the pipe.

johnjohn
  • 716
  • 2
  • 9
  • 17

1 Answers1

0

You could do as below.

dat |> 
  mutate(N= n(), .by=country)

output

  country values N
1     USA     25 2
2     USA     30 2
3   Japan     20 3
4   Japan     45 3
5   Japan     31 3
YH Jang
  • 1,306
  • 5
  • 15