私が扱っているデータセットは、顧客と月ごとの請求データです。最後に、元のデータセットのように、列名の行と月の顧客IDを持つデータフレームを作成したいと思います。しかし、この新しいデータセットには、顧客がその月に別の月に「獲得した」かどうかのダミー変数が含まれていることが必要です。彼らは前に請求されたことがなかったし、その月は彼らが請求された最初のものだった。ここでループ内に新しい列を作成または適用
が再現可能な例だけでなく、私が今書かれているループです:
set.seed(24)
example.data <- data.frame(
ID = sample(11:20),
Jan = sample(0:5, 10, replace = TRUE),
Feb = sample(0:5, 10, replace = TRUE),
Mar = sample(0:5, 10, replace = TRUE),
Apr = sample(0:5, 10, replace = TRUE)
)
gained.df.ex <- data.frame(example.data$ID)
## customers can't be gained in the first month
## there's no previous data to verify that this is the first time they've been billed, so all values are 0
gained.df.ex$Jan <- rep(0, length(example.data$ID)
## here's the loop that isn't working
for(i in 3:5){
new.month.dummy <- for (x in 1:length(gained.df.ex$example.data.ID)){
ifelse(example.data[x,i] == 0, new.month.dummy[x] <- 0, ifelse(sum(example.data[x,2:(i-1)]} == 0, new.month.dummy[x] <-1, new.month.dummy <- 0))
}
私は適用してこれを行う方法があります確信しているが、私はどのようにわかりません。
ようになります予想される出力は次のとおりです。
> example.data
Jan Feb Mar Apr
15 0 3 4 3
19 1 3 0 5
20 4 2 5 1
12 2 1 3 0
14 0 0 2 1
17 5 5 4 4
11 3 4 1 5
18 1 0 0 2
13 3 2 5 3
16 2 5 1 2
> gained.df.ex
Jan Feb Mar Apr
15 0 1 0 0
19 0 0 0 0
20 0 0 0 0
12 0 0 0 0
14 0 0 1 0
17 0 0 0 0
11 0 0 0 0
18 0 0 0 0
13 0 0 0 0
16 0 0 0 0
はあなたが唯一のIDごとに1つの行を持っていない例 – akrun
に基づいて予想される出力を投稿することができます試すことができますか? – rawr
予想される出力が質問に追加されました。 – Emma