[英]Convert a sequence to a sequence of ODD or Even in R
If I have a sequence of numbers within a dataframe - is it possible to create a new column that follows the sequence but shows only the odd or even - heres an example: 如果我在数据帧中有一个数字序列-是否可以在该序列之后创建一个新列,但仅显示奇数或偶数-这是一个示例:
SEQ ODDSEQ EVENSEQ
1 1 2
1 1 2
1 1 2
2 3 4
2 3 4
2 3 4
3 5 6
3 5 6
3 5 6
4 7 8
4 7 8
4 7 8
So SEQ is what I have right now...a repeated sequence, I'd like to create columns 2 & 3..? 所以SEQ是我现在拥有的...一个重复的序列,我想创建第2&3列。 I know Modulo is somehow involved bu I can quite get it.
我知道Modulo一定会参与其中,但我能完全做到这一点。
Any ideas..? 有任何想法吗..? Paul
保罗
Assuming that we need a general method 假设我们需要一个通用方法
library(dplyr)
df1 %>%
mutate(ODDSEQ = seq(1, length.out= n_distinct(SEQ), by = 2)[match(SEQ, unique(SEQ))],
EVENSEQ = seq(2, length.out = n_distinct(SEQ), by = 2)[match(SEQ, unique(SEQ))])
# SEQ ODDSEQ EVENSEQ
#1 1 1 2
#2 1 1 2
#3 1 1 2
#4 2 3 4
#5 2 3 4
#6 2 3 4
#7 3 5 6
#8 3 5 6
#9 3 5 6
#10 4 7 8
#11 4 7 8
#12 4 7 8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.