Home > Software design >  How to make column value a new row in r
How to make column value a new row in r

Time:05-28

I have a dataframe that I would like to reformat by making the first column its own row above the values.

I want this:

| Type | Value1 | Value2 |
| -----| ------ | ------ |
| A    | 1      | 3      |
| B    | 2      | 2      |

To become this with the rows containing "A" and "B" to be merged cells:

|      | Value1 | Value2 |
| -----| ------ | ------ |
| A                      |
|      | 1      | 3      |
| B                      |
|      | 2      | 2      |

CodePudding user response:

We could use insertRows function from berryFunctions package: For your original data you may adapt c(1,3) -> for example with a sequence:

library (berryFunctions)
librar(dplyr)

insertRows(df, c(1,3), new="") %>% 
  mutate(Type = lead(Type, default = ""))
  Type Value1 Value2
1    A              
2           1      3
3    B              
4           2      2
  • Related