Skip to content

Instantly share code, notes, and snippets.

@kazutan
Last active August 8, 2017 07:00
Show Gist options
  • Save kazutan/9323890aab2f0901fe32a6442cf886c3 to your computer and use it in GitHub Desktop.
Save kazutan/9323890aab2f0901fe32a6442cf886c3 to your computer and use it in GitHub Desktop.
library(dplyr)
library(tidyr)
#データセット準備
df1 <- data.frame(id = 101:106,
x1 = sample(1:2, 6, replace = TRUE))
#全て1の値の変数noを追加
# joinでうまく入ってくれるようにするため
df1 <- df1 %>%
mutate(no = 1)
#繰り返しの回数を準備
times <- 4
# idと繰り返しの回数との直積を出す(新しい複合キー)
# 詳しくは http://qiita.com/kazutan/items/ab81958994426e67e017#expand-crossing-nesting
hoge <- crossing(id = df1$id, no = 1:times)
# 新しいキーを利用して,データセットをjoin
df <- left_join(hoge, df1)
# 空欄を,同一のidのレコードでうまく埋める
# 詳しくは http://qiita.com/kazutan/items/ab81958994426e67e017#fill
df <- fill(df, x1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment