Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selected columns to new row

Tags:

r

dplyr

I'm trying to split columns into new rows keeping the data of the first two columns.

d1 <- data.frame(a=c(100,0,78),b=c(0,137,117),c.1=c(111,17,91), d.1=c(99,66,22), c.2=c(11,33,44), d.2=c(000,001,002))

d1
    a   b c.1 d.1 c.2 d.2
1 100   0 111  99  11   0
2   0 137  17  66  33   1
3  78 117  91  22  44   2

Expected results would be:

    a   b  c    d
1 100   0  111  99
2 100   0  11   0
3   0 137  17   66  
4   0 137  33   1
5  78 117  91   22  
6  78 117  44   2

Multiple tries with dplyr, but in sees is not the right approach.

like image 714
Felipe Reyes Avatar asked May 11 '20 17:05

Felipe Reyes


People also ask

How do I convert columns to rows cells?

Here's how you can transpose cell content: Copy the cell range. Select the empty cells where you want to paste the transposed data. On the Home tab, click the Paste icon, and select Paste Transpose.

Can you turn a column into a row in Excel?

In Excel, to convert any Columns to Rows, first select the column which you want to switch and copy the selected cells or columns. To proceed further, go to the cell where you want to paste the data. Then from the Paste option, which is under the Home menu tab, select the Transpose option.


2 Answers

If you want to stay in dplyr/tidyverse, you want tidyr::pivot_longer with a special reference to .value -- see the pivot vignette for more:

library(tidyverse)
d1 <- data.frame(
  a = c(100, 0, 78),
  b = c(0, 137, 117),
  c.1 = c(111, 17, 91),
  d.1 = c(99, 66, 22),
  c.2 = c(11, 33, 44),
  d.2 = c(000, 001, 002)
)

d1 %>% 
  pivot_longer(
    cols = contains("."),
    names_to = c(".value", "group"),
    names_sep = "\\."
  )
#> # A tibble: 6 x 5
#>       a     b group     c     d
#>   <dbl> <dbl> <chr> <dbl> <dbl>
#> 1   100     0 1       111    99
#> 2   100     0 2        11     0
#> 3     0   137 1        17    66
#> 4     0   137 2        33     1
#> 5    78   117 1        91    22
#> 6    78   117 2        44     2

Created on 2020-05-11 by the reprex package (v0.3.0)

like image 108
JasonAizkalns Avatar answered Oct 10 '22 11:10

JasonAizkalns


This could solve your issue:

#Try this
a1 <- d1[,c(1:4)]
a2 <- d1[,c(1,2,5,6)]
names(a1) <- names(a2) <- c('a','b','c','d')
DF <- rbind(a1,a2)
like image 1
Duck Avatar answered Oct 10 '22 10:10

Duck