0

I would like to calculate column D based on the date column A. Column D should represent the number of observations grouped by column B.

Edit: fake data below

 data <- structure(list(date = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 9L, 
    10L, 11L, 12L, 7L, 8L, 1L, 2L, 3L, 4L, 5L, 6L), .Label = c("1/1/2015", 
    "1/2/2015", "1/3/2015", "1/4/2015", "1/5/2015", "1/6/2015", "5/10/2015", 
    "5/11/2015", "5/6/2015", "5/7/2015", "5/8/2015", "5/9/2015"), class = "factor"), 
        Country = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 
        2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("A", "B", 
        "C"), class = "factor"), Value = c(215630672L, 1650864L, 
        124017368L, 128073224L, 97393448L, 128832128L, 14533968L, 
        46202296L, 214383720L, 243346080L, 85127128L, 115676688L, 
        79694024L, 109398680L, 235562856L, 235473648L, 158246712L, 
        185424928L), Number.of.Observations.So.Far = c(1L, 2L, 3L, 
        4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L
        )), class = "data.frame", row.names = c(NA, -18L))

What function in R will create a column D like so?

enter image description here

user6883405
  • 393
  • 3
  • 14

1 Answers1

0

We can group by 'Country' and create sequence column with row_number()

library(dplyr)
df1  %>%
   group_by(Country) %>%
   mutate(NumberOfObs = row_number())

Or with base R

df1$NumberOfObs <- with(df1, ave(seq_along(Country), Country, FUN = seq_along))

Or with table

df1$NumberOfObs <- sequence(table(df1$Country))

Or in data.table

library(data.table)
setDT(df1)[, NumberOfObs := rowid(Country)][]

data

df1 <- read.csv('file.csv')
akrun
  • 874,273
  • 37
  • 540
  • 662