Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
选择R中的中间n行_R_Data.table - Fatal编程技术网

选择R中的中间n行

选择R中的中间n行,r,data.table,R,Data.table,我在R中有一个data.table,比如df row.number <- c(1:20) a <- c(rep("A", 10), rep("B", 10)) b <- c(sample(c(0:100), 20, replace = TRUE)) df <-data.table(row.number,a,b) df row.number a b 1 1 A 14 2 2 A 59 3 3 A

我在R中有一个data.table,比如df

 row.number <- c(1:20)
 a <- c(rep("A", 10), rep("B", 10))
 b <- c(sample(c(0:100), 20, replace = TRUE))
 df <-data.table(row.number,a,b)
 df
   row.number a  b
1           1 A 14
2           2 A 59
3           3 A 39
4           4 A 22
5           5 A 75
6           6 A 89
7           7 A 11
8           8 A 88
9           9 A 22
10         10 A  6
11         11 B 37
12         12 B 42
13         13 B 39
14         14 B  8
15         15 B 74
16         16 B 67
17         17 B 18
18         18 B 12
19         19 B 56
20         20 B 21

row.number使用
setorder
进行排序,使用
.N
进行筛选:

setorder(df, b)[(.N/2 - 10/2):(.N/2 + 10/2 - 1), ]
   row.number a  b
1:         11 B 36
2:          5 A 38
3:          8 A 41
4:         18 B 43
5:          1 A 50
6:         12 B 51
7:         15 B 54
8:          3 A 55
9:         20 B 59
10:         4 A 60

您可以使用以下代码

library(data.table)

set.seed(9876) # for reproducibility

# your data
row.number <- c(1:20)
a <- c(rep("A", 10), rep("B", 10))
b <- c(sample(c(0:100), 20, replace = TRUE))
df <- data.table(row.number,a,b)
df

# define how many to select and store in n
n <- 10
# calculate how many to cut off at start and end
n_not <- (nrow(df) - n )/2

# use data.tables setorder to arrange based on column b
setorder(df, b)

# select the rows wanted based on n
df[ (n_not+1):(nr-n_not), ]
库(data.table)
设定种子(9876)#用于再现性
#你的数据
行数或
df[b>=中位数(b)]