Divide a single column in multiple column

Hi everybody!

I have a dataset like this:

Df <- data.frame(A=c(2,3,9,12,2,5,7,7,1,23,3,4,14,3,9,8,6,11,9,4),B=c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2))
Df
> Df
    A B
1   2 1
2   3 1
3   9 1
4  12 1
5   2 1
6   5 1
7   7 1
8   7 1
9   1 1
10 23 1
11  3 2
12  4 2
13 14 2
14  3 2
15  9 2
16  8 2
17  6 2
18 11 2
19  9 2
20  4 2

What I want is a dataset like this:

Df2 <- data.frame(A=c(2,3,9,12,2,5,7,7,1,23), B=c(3,4,14,3,9,8,6,11,9,4))
Df2 = t(Df2)
Df2 <- as.data.frame(Df2)
Df2
> Df2
  V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
A  2  3  9 12  2  5  7  7  1  23
B  3  4 14  3  9  8  6 11  9   4

So my goal is to transpose the column A in Df in Df2 and divide it in two rows according to the counter of column B in Df.

I try this command, but I don't know how to complete it:

Df %>% rowwise() %>% mutate(Pos=which(c_across(A:B) ??? )[1])

Thanks

One way to do it

library(tidyverse)

df <- data.frame(A=c(2,3,9,12,2,5,7,7,1,23,3,4,14,3,9,8,6,11,9,4),B=c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2))

df %>%
    mutate(B = if_else(B == 1, "A", "B")) %>% 
    group_by(B) %>% 
    mutate(var = paste0("V",row_number())) %>% 
    pivot_wider(id_cols = B, names_from = var, values_from = A) %>% 
    rename(row_name = B)
#> # A tibble: 2 x 11
#> # Groups:   row_name [2]
#>   row_name    V1    V2    V3    V4    V5    V6    V7    V8    V9   V10
#>   <chr>    <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 A            2     3     9    12     2     5     7     7     1    23
#> 2 B            3     4    14     3     9     8     6    11     9     4

Created on 2021-07-22 by the reprex package (v2.0.0)

I have the following error:
Error in rename(., row_name = B) : unused argument (row_name = B)

and your code works only with 2 rows... if I have more value in B in Df?

If you have additional requirements, feel free to ask a new question :smiley:

df %>%
    group_by(B) %>% 
    mutate(var = paste0("V",row_number())) %>% 
    pivot_wider(id_cols = B, names_from = var, values_from = A)

This part should work for any number of values in B, and then you can reformat as required.

If this doesn't solve your problem, please provide a more representative example of your issue.

1 Like

Hi,
Another way:

Df2 = sapply(levels(as.factor(Df$B)), FUN = function(x) Df$A[Df$B == x])
# eventually, if you want exactly what you said
Df2 = as.data.frame(t(sapply(levels(as.factor(Df$B)), FUN = function(x) Df$A[Df$B == x])), row.names = c("A","B"))

this is perfect! thank you very much

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.