Reputation: 2508
I have one dataframe DATA_SET
, which is composed of three columnsc(TEST1, TEST2, TEST3)
and a second dataframe DATA_SET1
which is composed of two columns c(key, value)
.
DATA_SET<-data.frame(
TEST1=c(200,220,200,260,300,290,320,320,360,400),
TEST2=c(200,220,200,260,400,290,220,370,260,200),
TEST3=c(200,220,200,260,500,290,120,240,160,400)
)
DATA_SET1<-data.frame(
key=c(rep("TEST1",10),rep("TEST2",10),rep("TEST3",10)),
value=c(700,700,700,700,700,700,700,700,700,700)
)
So my intention is to change DATA_SET1
with melt()
function or something similar and after that combine that with first table (i.e. DATA_SET
) to get a table like the one below.
Upvotes: 1
Views: 40
Reputation: 29153
You can do the following in base
r
.
unstack
takes care of "change DATA_SET1
with melt()
function or s̲o̲m̲e̲t̲h̲i̲n̲g̲ ̲si̲m̲i̲l̲a̲r̲" and rbind
is for "combine with first table (DATA_SET
)":
rbind(DATA_SET, unstack(DATA_SET1, form = value ~ key))
#> TEST1 TEST2 TEST3
#> 1 200 200 200
#> 2 220 220 220
#> 3 200 200 200
#> 4 260 260 260
#> 5 300 400 500
#> 6 290 290 290
#> 7 320 220 120
#> 8 320 370 240
#> 9 360 260 160
#> 10 400 200 400
#> 11 700 700 700
#> 12 700 700 700
#> 13 700 700 700
#> 14 700 700 700
#> 15 700 700 700
#> 16 700 700 700
#> 17 700 700 700
#> 18 700 700 700
#> 19 700 700 700
#> 20 700 700 700
Created on 2019-05-15 by the reprex package (v0.2.1)
Upvotes: 1
Reputation: 690
Using the tidyverse, tidyr
and dplyr
:
library(tidyr)
library(dplyr)
DATA_SET1 %>%
mutate(id = rep(1:10, 3)) %>%
spread(key, value) %>%
select(-id) %>%
bind_rows(DATA_SET)
Upvotes: 0