【问题标题】:How to create a column with information from other columns如何使用来自其他列的信息创建列
【发布时间】:2019-07-14 06:20:36
【问题描述】:

无法根据需要创建列。它包括使用流列的前第三个值,用于事件列的每个新值。

我试图通过使用 for 循环来解决这个问题,但不能完全复制我想要的。我在附近,但不在那里。

只是为了重新创建我生成以下数据框的示例

flow<- c(40, 39, 38, 37, 50, 49, 46, 44, 60, 55, 40, 70, 80, 75, 90, 88, 86, 100, 120, 118)
event<- c(1,1,1,1,2,2,2,2,3,3,3,4,5,5,6,6,6,7,8,8)
a<- data.frame(flow, event)

for (j in seq(1, length(a$event))) {
  if (a$event[j] <= 1){ 
   a$BF[a$event==j]<- NA}                  
else{ 
 if (a$event[j] == a$event[j-1]){
  a$BF[a$event==j]<- a$flow[j-3]
  } else{
  a$BF[j]<- a$flow[j-3] }
 }
}

I expected to generate a column called "BF" to be like this:
    flow event BF
1    40     1  NA
2    39     1  NA
3    38     1  NA
4    37     1  NA
5    50     2  39
6    49     2  39
7    46     2  39
8    44     2  39
9    60     3  49
10   55     3  49
11   40     3  49
12   70     4  60
13   80     5  55
14   75     5  55
15   90     6  70
16   88     6  70
17   86     6  70
18  100     7  90
19  120     8  88
20  118     8  88

我使用前面的代码获得的错误是没有正确复制与“事件”列匹配的值。 (应该如表所示)。

【问题讨论】:

  • 有点难以理解的逻辑。也许更清楚你如何获得新价值。例如,第 13 行的值从何而来?不应该是70吗?
  • 嗨,很抱歉没有说清楚,第 13 行中“bf”的值来自流的前第三个值(第 10 行的流值),依此类推“bf”列。其他示例是第 5 行。该行的 bf 值是流的第三个先前值(流第 2 行 = 39)。
  • 当“事件”列的数量发生变化时,“BF”列的新值应该开始(这将是“事件”列的前第三行的值流”栏)。这个“BF”值对于“event”列应该是相同的,直到“event”列发生变化,然后我们通过再次查找“flow”的前第 3 行来搜索“BF”的新值"列

标签: r for-loop


【解决方案1】:

更整洁的解决方案将是:

library(dplyr)
a %>% 
 mutate(BF = ifelse(event<=1,NA,row_number()-3)) %>% 
 group_by(event) %>%
 mutate(BF = BF[1]) %>%
 ungroup() %>%
 mutate(BF = a[BF,]$flow)

# A tibble: 20 x 3
    flow event    BF
   <dbl> <dbl> <dbl>
 1    40     1    NA
 2    39     1    NA
 3    38     1    NA
 4    37     1    NA
 5    50     2    39
 6    49     2    39
 7    46     2    39
 8    44     2    39
 9    60     3    49
10    55     3    49
11    40     3    49
12    70     4    60
13    80     5    55
14    75     5    55
15    90     6    70
16    88     6    70
17    86     6    70
18   100     7    90
19   120     8    88
20   118     8    88

【讨论】:

    【解决方案2】:

    使用tidyverse 获取输出的另一种方法。这将您的问题分为两部分。那里可能有更简洁的东西:

    library(tidyverse)
    critical_info <- a %>% 
      mutate(previous = lag(flow, 3)) %>% #find the previous flow number for each
      group_by(event) %>% 
      mutate(subevent = row_number()) %>% #to knew each subevent within an event
      filter(subevent == 1) %>% #filter out unimportant rows
      rename(BF = previous) %>% #rename the column
      select(event, BF) # get the right stuff
    
    a %>% 
      left_join(critical_info, by ="event")
    

    【讨论】:

      猜你喜欢
      • 2020-08-08
      • 1970-01-01
      • 2012-08-11
      • 1970-01-01
      • 2019-11-21
      • 2014-11-29
      • 2016-11-17
      • 2021-12-05
      • 2018-05-05
      相关资源
      最近更新 更多