Search code examples
rdataframerowmultiple-columns

columns to rows in r


I have a dataframe like this:

DATE CZK EUR USD
2021-07-25 25 15,5555684 4

And I want to turn it into this table:

DATE CP mnozstvi
2021-07-25 CZK 25
2021-07-25 EUR 15,5555684
2021-07-25 DOL 4

My data.frame is much larger, this is just minimal example. I seek some versatile solution. I managed to do that by function gather() like this:

data.frame %>% gather(CP,,CZK,EUR,USD) %>% rename(mnozstvi = value)

But it changed the numbers as some of them vere decimal adn I dnt know why. Any ideae how to do that easily? thank you.


Solution

  • You can try melt within data.table package

    > melt(setDT(df), id.vars = "DATE",variable.name = "CP",value.name = "mnozstvi")
             DATE  CP mnozstvi
    1: 2021-07-25 CZK 25.00000
    2: 2021-07-25 EUR 15.55557
    3: 2021-07-25 USD  4.00000
    

    or using stack

    > setDT(df)[,setNames(rev(stack(.SD)),c("CP","mnozstvi")),DATE]
             DATE  CP mnozstvi
    1: 2021-07-25 CZK 25.00000
    2: 2021-07-25 EUR 15.55557
    3: 2021-07-25 USD  4.00000