Search code examples
rdata.tabledcast

How to use dcast() to convert a 5x2 data.table to a 1x5 data.tabe?


I have the following data.table

DT

ABBREVIATION    FULL_TEXT
-----------------------------
    DCD         TEXT1
    PCK         TEXT2
    KLM         TEXT3
    NOP         TEXT4
    XYZ         TEXT5

I would like to transform the data.table such that each "ABBREVIATION" is it's own column name. And there's one row that details the "FULL_TEXT", so

DCD     PCK     KLM     NOP     XYZ
------------------------------------
TEXT1   TEXT2   TEXT3   TEXT4   TEXT5

I tried using

dcast(DT, FULL_TEXT ~ ABBREVIATION, value.var = "FULL_TEXT")

but that doesn't work. Thanks


Solution

  • dcast(df, 1 ~ ABBREVIATION, value.var = 'FULL_TEXT')[, -1, with = FALSE]
    #      DCD   KLM   NOP   PCK   XYZ
    # 1: TEXT1 TEXT3 TEXT4 TEXT2 TEXT5
    

    You should use transpose instead though

    data.table::transpose(df, make.names = 'ABBREVIATION')
    #      DCD   PCK   KLM   NOP   XYZ
    # 1: TEXT1 TEXT2 TEXT3 TEXT4 TEXT5
    

    Data used

    df <- fread('
    ABBREVIATION    FULL_TEXT
        DCD         TEXT1
        PCK         TEXT2
        KLM         TEXT3
        NOP         TEXT4
        XYZ         TEXT5
    ')