无法创建我想要的列。它在于对event列的每个新值使用flow列的前三个值。
我试图通过使用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我在前面的代码中得到的错误是没有正确地复制与"event“列匹配的值。(它应该如表中所示)。
发布于 2019-07-14 05:23:31
使用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")发布于 2019-07-14 06:20:36
更整洁的解决方案将是:
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 88https://stackoverflow.com/questions/57022691
复制相似问题