AriWhatElse
AriWhatElse

Reputation: 37

Expand the Dataframe - Adding Rows not Columns

I have a data frame with one variable which is for example the county ID. I have 401 County ID's, so I have 401 rows.

'data.frame':   401 obs. of  1 variable:
 $ KRS: num  1001 1002 1003 1004 1051 ...

head(fs)
   KRS
1 1001
2 1002
3 1003
4 1004
5 1051
6 1053

I want to add a Variable, which representing another "categorie" with 6 levels to expand the the data frame, so I got instead of 401 rows (observations) 401*6=2406 rows (observations).

It should look like this:

   KRS  V2
1  1001  1
2  1001  2
3  1001  3
4  1001  4
5  1001  5
6  1001  6
7  1002  1
8  1002  2
9  1002  3
10 1002  4
11 1002  5
12 1002  6

and so on....

I hope you understand what I mean and I hope you can help me.

Thank you!

Best regards

Ari

Upvotes: 0

Views: 286

Answers (3)

holzben
holzben

Reputation: 1471

You can use rep:

fd <- data.frame(
  KRS = rep(fd$KRS, each = 6),
  V2 = rep(1:6, length(fd$KRS))
)

fd
# KRS V2
# 1  1001  1
# 2  1001  2
# 3  1001  3
# 4  1001  4
# 5  1001  5
# 6  1001  6
# 7  1002  1
# 8  1002  2
# 9  1002  3
# 10 1002  4
# 11 1002  5
# 12 1002  6
# 13 1003  1
# 14 1003  2
# 15 1003  3
# 16 1003  4
# 17 1003  5
# 18 1003  6
# 19 1004  1
# 20 1004  2
# 21 1004  3
# 22 1004  4
# 23 1004  5
# 24 1004  6
# 25 1050  1
# 26 1050  2
# 27 1050  3
# 28 1050  4
# 29 1050  5
# 30 1050  6

Upvotes: 1

jmpivette
jmpivette

Reputation: 275

You can use tidyr::expand_grid()

library(tidyr)

expand_grid(KRS = fs$KRS,V2 = 1:6)

tidyr::expand():

fs %>% 
  tidyr::expand(KRS, V2 = 1:6)

Or even expand.grid() from base R

expand.grid(fs$KRS, 1:6)

Upvotes: 4

Karthik S
Karthik S

Reputation: 11548

Does this work:

library(dplyr)
library(tidyr)
df %>% uncount(weights = 6) %>% group_by(KRS) %>% mutate(V2 = row_number())
# A tibble: 36 x 2
# Groups:   KRS [6]
     KRS    V2
   <dbl> <int>
 1  1001     1
 2  1001     2
 3  1001     3
 4  1001     4
 5  1001     5
 6  1001     6
 7  1002     1
 8  1002     2
 9  1002     3
10  1002     4
# ... with 26 more rows

Data used:

df
   KRS
1 1001
2 1002
3 1003
4 1004
5 1051
6 1053

Upvotes: 2

Related Questions