首页 > 解决方案 > 有没有办法转置不同的列名

问题描述

有没有办法用不同的列名转置数据框例如

Col A   Col B
Table1  Date
Table1  Country
Table2  Name
Table2  Date
Table3  ID
Table3  Place

必需的输出(同名的列应在同一列中对齐,如日期)

Col A   Col1    Col2    Col3
Table1  Date    Country 
Table2  Date    Name    
Table3           ID    Place

标签: r

解决方案


似乎要获得所需的输出,您必须解决存在 > 1 个ColB值实例的情况以及分别只有 1 个实例的情况。

选项1:

library(data.table)
setDT(df)

df[, single := .N == 1L, ColB]
df[, b_id := frank(ColB, ties.method = 'dense')]

out <- 
  merge(
    dcast(df[single == F], ColA ~ b_id, value.var = 'ColB'),
    dcast(df[single == T], ColA ~ rowid(ColA), value.var = 'ColB'),
    by = 'ColA',
    all = T
  )

setnames(out, replace(paste0('Col', seq(0, ncol(out) - 1)), 1, names(out)[1]))

out
#      ColA Col1    Col2  Col3
# 1: Table1 Date Country  <NA>
# 2: Table2 Date    Name  <NA>
# 3: Table3 <NA>      ID Place

选项 2:

library(data.table)
setDT(df)    

df[, single := .N == 1L, ColB]
df[, b_id := 
       interaction(single, fifelse(single, rowid(ColA), frank(ColB, ties.method = 'dense')))]

dcast(df, ColA ~ paste0('Col', as.integer(b_id)), value.var = 'ColB')


#      ColA Col2 Col3    Col4
# 1: Table1 <NA> Date Country
# 2: Table2 Name Date    <NA>
# 3: Table3   ID <NA>   Place

输入数据:

df <- fread('
ColA   ColB
Table1  Date
Table1  Country
Table2  Name
Table2  Date
Table3  ID
Table3  Place
')

推荐阅读