Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

expand a data frame in R

Writer Matthew Martinez

I have a data frame like below:-

 Var1 Var2 1 a a 2 a b 3 b a 4 b b

I want an ID column containing values 1 and 2. How do I expand the above data frame so that the final data frame looks something like this?

 Var1 Var2 ID 1 a a 1 2 a b 1 3 b a 1 4 b b 2 1 a a 2 2 a b 2 3 b a 2 4 b b 2

Ahh thanks to MKR, the issue is due to the package.

 library(dplyr)
df <- read.table(text = "Var1 Var2 1 a a 2 a b 3 b a 4 b b", header = TRUE, stringsAsFactors = FALSE)
df %>% group_by(Var1, Var2) %>% expand(ID = 1:2) %>% arrange(ID)
2

3 Answers

Many options available to get the desired result. But perhaps OP seems to be keen on using tidyr::expand. A solution can be as:

library(dplyr)
library(tidyr)
df %>% group_by(Var1, Var2) %>% expand(ID = 1:2) %>% arrange(ID)
# # A tibble: 8 x 3
# # Groups: Var1, Var2 [4]
# Var1 Var2 ID
# <chr> <chr> <int>
# 1 a a 1
# 2 a b 1
# 3 b a 1
# 4 b b 1
# 5 a a 2
# 6 a b 2
# 7 b a 2
# 8 b b 2

Data:

df <- read.table(text =
"Var1 Var2 1 a a 2 a b 3 b a 4 b b",
header = TRUE, stringsAsFactors = FALSE)
8

tidyr::expand did not work for me. However, tidyr::crossing worked like a charm.

The solution using crossing is:

library(tidyr)
library(dplyr)
df %>% crossing(ID = c(1:2)) %>% arrange(ID)
# # A tibble: 8 x 3
# Var1 Var2 ID
# <chr> <chr> <int>
# 1 a a 1
# 2 a b 1
# 3 b a 1
# 4 b b 1
# 5 a a 2
# 6 a b 2
# 7 b a 2
# 8 b b 2

Data (gratefully copied from MKR <3):

df <- read.table(text =
"Var1 Var2 1 a a 2 a b 3 b a 4 b b",
header = TRUE, stringsAsFactors = FALSE)

Here's something quite general:

library(dplyr)
x <- head(cars,2)
bind_rows(replicate(3,x,simplify = FALSE),.id="ID")
# ID speed dist
# 1 1 4 2
# 2 1 4 10
# 3 2 4 2
# 4 2 4 10
# 5 3 4 2
# 6 3 4 10

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.