R 数据帧中的中值

R 数据帧中的中值,r,dataframe,R,Dataframe,我想计算以下数据框的中值 index t1 t2 t3 t4 10 1 4 7 10 20 2 5 8 11 30 3 6 9 0 40 1 0 0 0 我遵循以下步骤: 步骤1:按列求和 index t1 t2 t3 t4 sum 10 1 4 7 10 22 20 2 5 8 11 26 30 3 6 9 0 18 40 0

我想计算以下数据框的中值

index t1 t2 t3 t4
    10  1  4  7 10
    20  2  5  8 11
    30  3  6  9  0
    40  1  0  0  0
我遵循以下步骤:

步骤1:按列求和

index  t1   t2  t3  t4  sum
    10  1    4   7   10  22
    20  2    5   8   11  26
    30  3    6   9   0   18
    40  0    1   0   0   1
 
步骤2:排序和变量

index  t1   t2  t3  t4  sum
   40  0    0   0   10  1
   30  3    6   9   0   18
   10  1    4   7   10  22
   20  2    5   8   11  26
步骤3:计算指数变量的中位数

median of index = (30 + 10) / 2 =20
步骤4:返回具体的索引值

Median(df)=20
我不知道如何计算步骤3和步骤4

样本数据:

df<-structure(list(index=c (10,20,30,40), 
                   t1 = c(1, 2, 3, 1), 
                   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

df你的问题没有很好的定义,所以我有点随意

  • df$sum=rowSums(子集(df,select=-c(索引)))
  • df=df[订单(df$sum),]
  • idx=中值(df$指数)
    (您的计算是“错误的”)
  • which.min(abs(df$index idx))

  • 它返回2,即在排序数据帧中最接近“中值”索引的索引。

    只需使用sapply和中值函数即可。使用mtcars的示例:

    medians <- sapply(mtcars, median)
    
    中位数