简体   繁体   English

R:想要将数据表中的列中的数据复制到特定的行中

[英]R: Want to copy data from columns in a data table into specific rows

I currently have multiple data tables which look like this:我目前有多个数据表,如下所示:

First Quartile第一个四分位数

Q1DT = data.table(
  Tree = c("Cherry", "Birch", "Oak"), 
  Height = c("1m", "3m", "5m"), 
  Age = c(10L, 12L, 15L)
)
Q1DT
#      Tree Height Age
# 1: Cherry     1m  10
# 2:  Birch     3m  12
# 3:    Oak     5m  15

Mean意思是

AVGDT = data.table(
  Tree = c("Cherry", "Birch", "Oak"), 
  Height = c("2m", "5m", "7m"), 
  Age = c(13L, 17L, 19L)
)
AVGDT
#      Tree Height Age
# 1: Cherry     1m  10
# 2:  Birch     3m  12
# 3:    Oak     5m  15

Quartile 3四分位数 3

Q3DT = data.table(
  Tree = c("Cherry", "Birch", "Oak"), 
  Height = c("7m", "10m", "25m"), 
  Age = c(17L, 22L, 25L)
)
Q3DT
#      Tree Height Age
# 1: Cherry     1m  10
# 2:  Birch     3m  12
# 3:    Oak     5m  15

I want to combine them so they look like this:我想将它们组合起来,使它们看起来像这样:

    Tree     Measure  Q1  Q2  Q3
    Cherry   Height    
    Cherry   Age
    Birch    Height
    Birch    Age
    Oak      Height
    Oak      Age  

I used the following to make the bare-bones of the table:我使用以下内容制作了表格的基本结构:

output.complete <- data.table(Tree= rep(trees.quartile.1$Tree, each = 2), measure = c(rep(c("Height", "Age"), times = length(unique(trees.quartile.1$Tree)))))

However, I cannot work out how to populate this table now from the data in the separate quartile data tables.但是,我现在无法从单独的四分位数数据表中的数据中计算出如何填充此表。 Any help would be massively appreciated!任何帮助将不胜感激!

There are a couple of ways to do this.有几种方法可以做到这一点。 I'm going to use rbind , melt , and dcast to reshape your data:我将使用rbindmeltdcast来重塑您的数据:

stack = rbind(Q1 = Q1DT, AVG = AVGDT, Q3 = Q3DT, idcol = 'stat')

# this will give a warning -- in the input, 'Age' is
#   an integer, and 'Height' is a character, so melt
#   must force 'Age' to be a character to proceed
out = stack[ , melt(.SD, id.vars = c('stat', 'Tree'), variable.name = 'Measure')
             ][ , dcast(.SD, Tree + Measure ~ stat, value.var = 'value')]
#      Tree Measure AVG Q1  Q3
# 1:  Birch  Height  5m 3m 10m
# 2:  Birch     Age  17 12  22
# 3: Cherry  Height  2m 1m  7m
# 4: Cherry     Age  13 10  17
# 5:    Oak  Height  7m 5m 25m
# 6:    Oak     Age  19 15  25

We can either use setcolorder afterwards to get the columns in the desired order, or define stat to be a factor in stack with the right order:我们可以在之后使用setcolorder以所需的顺序获取列,或者将stat定义为具有正确顺序的stack中的一个因素:

stack[ , stat := factor(stat, levels = c('Q1', 'AVG', 'Q3'))]

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

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