Prometheus
Prometheus

Reputation: 693

R fill columns n times

Hi I want to simulate a dataset like this:

City    Person
  1        1          
  1        2
  1        3
  2        1
  2        2
  2        3

Where City ID can go from 1-30 and Person ID from 1-40. I know that I can create City by the following code:

data=data.frame(City=rep(1:30,40),Person=0)

However, I cannot figure out how to assign the Person variable for each City ID without using a loop. How do I assign the Person IDs from 1-40 for each City ID? Any help will be appreciated. Thanks.

Upvotes: 1

Views: 47

Answers (1)

akrun
akrun

Reputation: 886938

We can do this with

df1$Person <- with(df1, ave(seq_along(City), City, FUN = seq_along))

Or

df1$Person <- sequence(table(df1$City))

Also, an easier expansion would be

expand.grid(City = 1:30, Person = 1:3)

Or with tidyverse

library(tidyverse)
crossing(City = 1:30, Person = 1:3)

Or using tidyverse

library(tidyverse)
df1 %>%
   group_by(City) %>%
   mutate(Person = row_number())

Or using data.table

library(data.table)
setDT(df1)[, Person := seq_len(.N), by = City]

data

df1 <- data.frame(City = rep(1:2, each = 3))

Upvotes: 1

Related Questions