0

I am trying to merge one column into another column. I want to merge the column "type0" into "type", while put the "type0" values to "days", with corresponded type = 0.

The original dataset would be like:

|id|type|days|type0|
|--|-----|----|----|
|1|1|10|10|
|1|2|3|5|
|2|1|2|6|
|2|2|6|8|

where type0 indicates that the subject has experienced x days with type 0 (i.e. subject 1 experienced 10 days of type 0)

The expected outcome would be like:

|id|type|days|
|--|-----|----|
|1|1|10|
|1|2|3|
|1|0|10|
|2|0|5|
|2|1|2|
|2|0|6|
|2|2|6|
|2|0|8|

Thank you all!

xshbj
  • 83
  • 6
  • Please provide a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) so we can help you with your question. – Desmond Nov 15 '21 at 03:32
  • I'm guessing there should be a 1 in the fourth row of the first column of your second table? – Mikael Jagan Nov 15 '21 at 04:52

2 Answers2

0

How about this?

library("dplyr")

d1 <- data.frame(
  id = c(1L, 1L, 2L, 2L),
  type = c(1L, 2L, 1L, 2L),
  days = c(10, 3, 2, 6),
  type0 = c(10, 5, 6, 8)
)
d2 <- d1 %>%
  select(-type0) %>%
  bind_rows(d1 %>% mutate(type = 0L, days = type0) %>% select(-type0)) %>%
  arrange(id, type, days)
d2

Here is the output:

  id type days
1  1    0    5
2  1    0   10
3  1    1   10
4  1    2    3
5  2    0    6
6  2    0    8
7  2    1    2
8  2    2    6
Mikael Jagan
  • 9,012
  • 2
  • 17
  • 48
0

You may try

Data

dummy <- read.table(text = "id  type    days    type0
1   1   10  10
1   2   3   5
2   1   2   6
2   2   6   8", header = T)

Code

library(dplyr)
dummy %>%
  mutate(days = type0,
         type = 0) %>%
  rbind(., dummy) %>%
  select(-type0)
  id type days
1  1    0   10
2  1    0    5
3  2    0    6
4  2    0    8
5  1    1   10
6  1    2    3
7  2    1    2
8  2    2    6
Park
  • 14,771
  • 6
  • 10
  • 29