我有一个数据框
structure(list(id = c(31068L, 4741L, 31068L, 48783L, 48783L,
4741L, 40866L, 602L, 43498L, 602L, 47365L, 27643L, 30657L, 47365L,
2456L, 30657L, 48783L, 40866L, 31068L, 31068L), chrom = structure(c(10L,
2L, 10L, 18L, 18L, 2L, 1L, 12L, 15L, 12L, 3L, 14L, 13L, 3L, 5L,
13L, 18L, 1L, 10L, 10L), .Label = c("chr1", "chr10", "chr11",
"chr12", "chr13", "chr14", "chr15", "chr16", "chr17", "chr18",
"chr19", "chr2", "chr3", "chr4", "chr5", "chr6", "chr7", "chr8",
"chr9", "chrM", "chrUn", "chrX", "chrY"), class = "factor"),
strand = structure(c(2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L,
1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L), .Label = c("-",
"+"), class = "factor"), position = c(32233920L, 63320175L,
32233915L, 105252695L, 105252690L, 63320180L, 160222550L,
60750690L, 111386910L, 60750685L, 89019895L, 155820080L,
146439265L, 89019890L, 56738465L, 146439260L, 105252700L,
160222545L, 32233910L, 32233925L), state = c(1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L), probability = c(0.0609068958401659, 0.0652616906258002,
0.0692068771991058, 0.0692812165331229, 0.0701354955671266,
0.0703768347393804, 0.0711103024384338, 0.0741845396230543,
0.0743938664894217, 0.0749688062517259, 0.079612884618025,
0.0813520378059492, 0.0826542716746912, 0.0846949902404464,
0.0861396527789957, 0.0864410597153605, 0.0871058913414357,
0.087430325878555, 0.0878512688974869, 0.0880022007028806
), differential = c(-0.23435362433765, -0.23435362433765,
-0.171785943061141, 0.196483908128415, 0.251738193935959,
-0.23435362433765, -0.23435362433765, -0.278594311118605,
0.242648431724363, -0.278594311118605, -0.278594311118605,
0.209140348612477, -0.28152682524624, -0.234047089198976,
0.290374904597332, -0.242344380735883, 0.196483908128415,
-0.23435362433765, -0.171785943061141, -0.155502764975432
), tag1 = c(0L, 0L, 0L, 15L, 15L, 0L, 0L, 5L, 30L, 5L, 5L,
10L, 2L, 3L, 15L, 7L, 15L, 0L, 0L, 0L), mut1 = c(0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L), tag2 = c(15L, 15L, 11L, 5L, 2L, 15L, 15L, 25L,
15L, 25L, 25L, 0L, 21L, 19L, 0L, 25L, 5L, 15L, 11L, 10L),
mut2 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), group = c(1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)), .Names = c("id",
"chrom", "strand", "position", "state", "probability", "differential",
"tag1", "mut1", "tag2", "mut2", "group"), class = c("data.table",
"data.frame"), row.names = c(NA, -20L), .internal.selfref = <pointer: 0x102819778>)
我想创建一个新列df$bin
,以便bin列创建长度为n的连续值的bin。
例如,如果n = 2,我希望有2个bin,bin列看起来像bin = c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2)
这样df$bin
的值将为1:n
,每个值将重复nrow(df)/n
次。
答案 0 :(得分:4)
您可以使用基本R函数cut
:
df$bin = cut(1:nrow(df), breaks = 2, labels = FALSE)