首页 > 解决方案 > 仅基于两列 Rstudio 从长格式到宽格式

问题描述

这是我的数据框: 我的数据框

我有一个六列的数据框,最后一列包含这些值。列“代码”包括 s 和 d。“性别”列包括 M 和 F。我在后代列中有两千个后代。

seq parent code Sex offspring                     Value 

1   49032   s   M   J44010_CCG7YANXX_2_661_X4   -0.38455056

2   48741   s   M   J44010_CCG7YANXX_2_661_X4   0.10574340

3   48757   s   M   J44010_CCG7YANXX_2_661_X4   0.39572906

4   48465   d   f   J44010_CCG7YANXX_2_661_X4   0.43409006

5   48521   d   f   J44010_CCG7YANXX_2_661_X4   0.40337447

6   48703   d   f   J44010_CCG7YANXX_2_661_X4   -0.38148980

parent 列包含男性和女性的 ID。我想在雄性/父亲旁边保留雌性/雌性 ID、雌性/雌性代码和雌性/雌性/雌性作为一列,并分别保留雄性值和雌性值。因此,“价值”将分为两部分。

数据框将如下所示:

'seq''parent1''sirecode''Sex''parent2''damcode''Sex''offspring''sireValue' 'damvalue'

  1    49032      s       M    48465     d       f    J44010  -0.38455056  0.43409006

  2    48741      s       M    48521     d       f    J44010   0.10574340   0.40337447

  3    48757      s       M    48703     d       f    J44010   0.39572906   -0.38148980

因此,每个后代将有 3 或 4 对父母。
我试图dcast在它上面使用函数。

标签: r

解决方案


我们可以dcast在创建序列列之后使用

library(data.table)
setDT(df1)[, n := seq_len(.N), .(code, Sex)]
dcast(df1, n + offspring ~ rowid(n), value.var = c('parent', 'code', 'Sex', 'Value'), sep = "")
#  n                 offspring parent1 parent2 code1 code2 Sex1 Sex2     Value1     Value2
#1: 1 J44010_CCG7YANXX_2_661_X4   49032   48465     s     d    M    f -0.3845506  0.4340901
#2: 2 J44010_CCG7YANXX_2_661_X4   48741   48521     s     d    M    f  0.1057434  0.4033745
#3: 3 J44010_CCG7YANXX_2_661_X4   48757   48703     s     d    M    f  0.3957291 -0.3814898

base R,我们可以使用reshape

df1$n <- with(df1, ave(seq_along(Sex), Sex, FUN = seq_along))
df1$n1 <- with(df1, ave(n, n, FUN = seq_along))
reshape(df1[-1], idvar = c('n', 'offspring'), timevar = 'n1', direction = 'wide' )

数据

df1 <- structure(list(seq = 1:6, parent = c(49032L, 48741L, 48757L, 
48465L, 48521L, 48703L), code = c("s", "s", "s", "d", "d", "d"
), Sex = c("M", "M", "M", "f", "f", "f"), 
  offspring = c("J44010_CCG7YANXX_2_661_X4", 
"J44010_CCG7YANXX_2_661_X4", "J44010_CCG7YANXX_2_661_X4", 
  "J44010_CCG7YANXX_2_661_X4", 
"J44010_CCG7YANXX_2_661_X4", "J44010_CCG7YANXX_2_661_X4"), 
   Value = c(-0.38455056, 
0.1057434, 0.39572906, 0.43409006, 0.40337447, -0.3814898)),
 class = "data.frame", row.names = c(NA, -6L))

推荐阅读