新的重叠变量

时间:2012-04-22 17:12:15

标签: r plyr data-management

我不知道该怎么称呼它。

我有人,年和活动的数据集

df <- data.frame("id" = c("1", "1", "1", "2", "2","3"), "years" = rep(1971, 6),
                      "activity" = c("a","b","c","d","e","e"))
  id years activity
1  1  1971        a
2  1  1971        b
3  1  1971        c
4  2  1971        d
5  2  1971        e
6  3  1971        e

我想结合年份和活动列,但是对于每年,在原始年份列中,我想生成+/- 3年,同时保留与id的关联

如果我分两步完成: 对于id“1”,原始年份是1971年,因此ID 1的+/- 3年将导致:

 id   all_years 
 1    1968
 1    1969
 1    1970
 1    1971
 1    1972
 1    1973
 1    1974

在第2步中,我想将此all_years列与原始df中的activities列结合起来,保留id。所以id“1”有3个活动(a,b,c)和7年(1968:1964),所以id“1”在新的组合列中会出现10次。

所以最终,我最终会得到这样的东西:

  id   year_and_activities 
  1    a
  1    b
  1    c
  1    1968
  1    1969
  1    1970
  1    1971
  1    1972
  1    1973
  1    1974
  2    d
  2    e
  2    1968
...
  2    1974
...
  3    e
...

一如既往,谢谢!

1 个答案:

答案 0 :(得分:1)

我无法真正关注您的问题,但考虑到初始数据框,您可以使用melt获取最终数据框:

require(reshape2)

##To get your +/- 3
dd = data.frame(id=df$id, activity=df$activity,
   years=df$years- rep(-3:3, nrow(df)))

##Pretty much gives you what you want
df_melt = melt(dd, id=1)

##Remove the unnecessary column
df_melt = df_melt[,c(1,3)]
##Rename 
colnames(df_melt) = c("id","year_and_activities")

##Order the column
df_melt[with(df_melt, order(id, year_and_activities)),]

顺便说一句,我建议把一个专栏作为“人物”和“年”的混合可能是一个坏主意 - 但你可能有充分的理由。