r-计算data.frame列的中值

  • 本文关键字:frame 计算 data r dataframe
  • 更新时间 :
  • 英文 :


我有下面的数据帧,我想确定索引的中值。例如,让我们考虑下面的数据.farme.

index t1 t2 t3 t4
10  1  4  7 10
20  2  5  8 11
30  3  6  9  0
40  0  0  0  0 

first step,中,我想按data.frame.的列相加

index t
10    22
20    26
30    18
40    0

second step中,我想确定指数的中位数。在这个过程中,我需要按递增顺序排列t,并选择中值。

index t
40    0
30    18
10    22
20    26

我知道R中有一个中值函数,但我得到了不同的结果。

样本数据:

df<-structure(list(index=c (10,20,30,40), 
t1 = c(1, 2, 3, 0), 
t2 = c(4, 5, 6, 0), 
t3 = c(7, 8,9,  0),
t4 = c(10, 11, 0, 0)), row.names = c(NA,4L), class = "data.frame")

df

我会试试这个:

library(data.table)
df <- setDT(df)
df_c <- df[,t:=t1+t2+t3+t4][, .(index, t)]
setorder(df_c, index)
median(df_c$index)

对于中位数,我实际上会使用一个函数并应用于索引列。

步骤1:使用apply函数

df$t<-apply(df[,c("t1","t2","t3","t4")],1,sum)
df
#          index t1 t2 t3 t4  t
#        1    10  1  4  7 10 22
#        2    20  2  5  8 11 26
#        3    30  3  6  9  0 18
#        4    40  0  0  0  0  0

步骤2:按列排序";t〃;使用order功能

df<-df[order(df$t),]
df
index t1 t2 t3 t4  t
# 4    40  0  0  0  0  0
# 3    30  3  6  9  0 18
# 1    10  1  4  7 10 22
# 2    20  2  5  8 11 26

步骤3计算median(我刚刚看到Peter的答案,我同意他的观点,中值应该是25(:

median(df$index)
# [1] 25

最新更新