将列添加到r中的正序或负序

jv4diomz  于 2023-03-27  发布在  其他
关注(0)|答案(1)|浏览(126)

我想在我的列中添加负序列或正序列。实际上,对于每个ID,如果col_int==1,则在值1之前的行上放置负序列,并在值1之后的行上放置负序列。

dfs <- data.frame(ID = c(rep("ID1",11),rep("ID2",4), rep("ID3",6)) , col_int=c(c(0,0,0,0,0,1,0,0,0,0,0),c(1,0,0,0),c(0,0,1,0,1,1) )) dfs_out <- dfs %>% mutate(col_out = c(c(seq(-5,-1)),1,c(seq(1,5)), c(1,1,2,3),c(-2,-1,1,1,2,3)))
wbrvyc0a

wbrvyc0a1#

试试看

library(dplyr)# version>= 1.1.0
 dfs_out %>% 
  mutate(col_out2 = (row_number() - match(1, col_int)) + 
    (col_int == 1 & !duplicated(col_int)), .by = ID)
  • 输出
ID col_int col_out col_out2
1  ID1       0      -5       -5
2  ID1       0      -4       -4
3  ID1       0      -3       -3
4  ID1       0      -2       -2
5  ID1       0      -1       -1
6  ID1       1       1        1
7  ID1       0       1        1
8  ID1       0       2        2
9  ID1       0       3        3
10 ID1       0       4        4
11 ID1       0       5        5
12 ID2       1       1        1
13 ID2       0       1        1
14 ID2       0       2        2
15 ID2       0       3        3
16 ID3       0      -2       -2
17 ID3       0      -1       -1
18 ID3       1       1        1
19 ID3       0       1        1
20 ID3       1       2        2
21 ID3       1       3        3

相关问题