简体   繁体   English

根据R中的范围类别创建汇总表

[英]Creating a summary table based on range categories in r

My data is in the following format: 我的数据采用以下格式:

input<-data.frame(
    region=c("A","T","R","R","T"),
    geomorph=c("F","F","S","S","P"),
    depth=c(2.6,3.5,5.8,6.7,8.9))

> input
  region geomorph depth
1      A        F   2.6
2      T        F   3.5
3      R        S   5.8
4      R        S   6.7
5      T        P   8.9

I would like to create a summary table such that for the given depth categories (ie 0-3,3-6,6-10) the number of entries for region (ie A,R,T) and geomorphology (ie F,S,P) are counted and presented as follows: 我想创建一个汇总表,以便对于给定的深度类别(即0-3,3-6,6-10),区域(即A,R,T)和地貌(即F,S)的条目数,P)计数并显示如下:

output<-data.frame(
    depth.category=c("0-3","3-6","6-10"),
    total=c(1,2,2),
    A=c(1,0,0),
    R=c(0,1,1),
    T=c(0,1,1),
    F=c(1,1,0),
    S=c(0,1,1),
    P=c(0,0,1))

> output
  depth.category total A R T F S P
1            0-3     1 1 0 0 1 0 0
2            3-6     2 0 1 1 1 1 0
3           6-10     2 0 1 1 0 1 1

Any suggestions how to go about this? 任何建议如何去做?

First, just create your intervals using cut , and then use table and cbind the results: 首先,只需使用cut创建您的间隔,然后使用table并将结果cbind

intervals <- cut(input$depth, breaks=c(0, 3, 6, 10))

cbind(table(intervals),
      table(intervals, input$region),
      table(intervals, input$geomorph))
#          A R T F P S
# (0,3]  1 1 0 0 1 0 0
# (3,6]  2 0 1 1 1 0 1
# (6,10] 2 0 1 1 0 1 1

The output of the above is a matrix . 上面的输出是一个matrix Use the following if you want a data.frame : 如果需要data.frame请使用以下data.frame

temp <- cbind(table(intervals),
      table(intervals, input$region),
      table(intervals, input$geomorph))

temp <- data.frame(depth.category = rownames(temp),
                   as.data.frame(temp, row.names = 1:nrow(temp)))
names(temp)[2] <- "Total"
temp
#   depth.category Total A R T F P S
# 1          (0,3]     1 1 0 0 1 0 0
# 2          (3,6]     2 0 1 1 1 0 1
# 3         (6,10]     2 0 1 1 0 1 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM