【问题标题】:Forming a new dataframe from the old data frame using for-loop使用for循环从旧数据帧形成新数据帧
【发布时间】:2019-06-21 09:50:45
【问题描述】:

我的数据框“c1”

 steps interval
   <dbl>    <int>
 1     0        0
 2     0        5
 3     0       10
 4     0       15
 5     0       20
 6     0       25
 7     0       30
 8     0       35
 9     0       40
10     0       45
# ... with 278 more rows

PS: Sorry for providing only a small sample from data

我想通过为每个 50 的间隔添加“间隔”列的行来创建一个新的数据框“c11”,以便相应地计算每 50 步(列步)的总和。

我的新数据框应该是这样的

 steps interval
   <dbl>    <int>
 1     0        0
 2     0        50
 3     0       100
 4     10      150
 5     0       200
 6     6       250
 7     20      300
 8     0       350
 9     230     400
10     0       450

我的代码

n=0
j=0
y <- nrow(c1)/50
class(n)
c11 <- data.frame(matrix(NA, nrow = y, ncol = 2)) 

class(c11)
for (i in 1:nrow(c1)) {
  n <- n + c1[i,1]
  if (i%%50==0)
  {
    c11[j,1]<- i
    c11[j,2] <- n
    j <- j+1
    n = 0
  }

}

有人可以更正显示错误输出的代码吗?

【问题讨论】:

  • 不清楚您要做什么。请尝试更好地解释它

标签: r loops dataframe for-loop


【解决方案1】:

尝试在aggregate 中使用cut

with(c1, aggregate(list(steps = steps), 
     list(interval = cut(interval, c(seq(min(interval), max(interval), 50), Inf), 
     labels = seq(min(interval), max(interval), 50), include.lowest = TRUE)), sum))

为了更明确,我们可以将步骤分开

c1$group <- cut(c1$interval, c(seq(min(c1$interval), max(c1$interval), 50), Inf),
      labels = seq(min(c1$interval), max(c1$interval), 50), include.lowest = TRUE)

aggregate(steps~group, c1, sum)

【讨论】:

  • @AnanyaVidyanathan 你能解释一下not working 是什么意思吗?您是否收到任何错误消息或错误答案?我在早期版本中也有一个错字。我现在已经更正了。你能再试一次吗?
  • 错误:在 aggregate.data.frame(as.data.frame(x), ...) 中:没有要聚合的行
  • @AnanyaVidyanathan 我用cut 创建了一个新列。你现在可以试试,让我知道。
  • 是的@Ronak Shah,它工作得很好……谢谢,伙计……顺便说一句,我的代码有什么问题吗?
  • @AnanyaVidyanathan 我可以看到您正在迭代每一行看起来不正确的每一行,因为您希望每 50 个 sum 而不是行。同样通常,在 R 中,大多数时候你可以不用循环使用像 aggregate/dplyr 这样的函数
猜你喜欢
  • 1970-01-01
  • 2020-08-14
  • 1970-01-01
  • 1970-01-01
  • 2020-12-06
  • 2021-09-26
  • 2021-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多