如何合并长度不等但已知块长度的数据帧?

时间:2019-02-18 15:56:40

标签: r dataframe

我有一个个体可以死亡和繁殖的模型。我按设定的时间间隔记录来自模型的信息。我知道个人的身份和从中采样的迭代次数:

        public  T GetValue<T>(string key)
        {
            if (_cache.containsKey(key))
            {
                // 99% of the time will hit this
                return _cache.GetItem(key);
            }

            return _api.GetValue(key).GetAwaiter().GetResult();

        }

但是每个人都有一个我要跟踪的数字列表。因为每个人都有一个以上的关联数字,所以我得到了两个样本大小不相等的数据帧。

df1<-data.frame(
who= c(1,2,3,4,1,2,3,3,5),
iteration = c(1,1,1,1,2,2,2,3,3)
)
df1

我想绑定它们,以便'who'变量与其值匹配。我进行了以下操作,将值分成大小合适的块,但现在我陷入了困境。

df2 <- data.frame(values=c(1,1, # id = 1
                           1,2, # id = 2
                           2,1, # id = 3
                           0,0, # id = 4
                           1,1, # id = 1
                           1,2, # id = 2
                           2,1, # id = 3
                           2,1, # id = 3
                           0,0)) # id = 5
df2

我应该得到一些像这样的东西:

df3 <- split(df2$values, ceiling(seq_along(df2$values)/2))

1 个答案:

答案 0 :(得分:1)

在这里,我们基于split创建的分组索引%%listvector中的分组索引中的“值”列,然后将{{1} },将list分配给NA个元素的最大length<-

,在元素末尾加length(如果元素数量较少)
list