Home > Software engineering >  How to merge one column into another column in r
How to merge one column into another column in r

Time:11-15

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!

CodePudding user response:

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

CodePudding user response:

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
  •  Tags:  
  • r
  • Related