converting long to wide

Hi Everyone,

I am wondering if anyone can help to suggest the way to reshape or reframe data from long to wide.
I attached jpg for your review.

Not sure how to do it.

I appreciate any help.

Typically tidyverse package containing pivot_wider would be recommended.

Study the examples.
If you require further assistance, please provide a reprex, neither excel nor jpg/image is a good format for the task of communicating with the forum.

Hi Nirgrahamuk,
Thanks for your response. Could please suggest the code or script for me to start with?

I dont think you've spent any significant time reading the content that I linked you to ...

I tried, but it gives me this one:

sorry I am just a beginner. Hope you can help. Many thanks

p.s. I wouldnt ever use such code; but only because I wouldnt aim for the sort of result you asked for; though appreciate I may be taking your ask too literally.


(an_example_input <- tibble(

true_sources <- c("SP1","SP2")

(fixed_1 <- an_example_input |>
  mutate(switched=Target %in% true_sources,
         osource = Source,
         otarget= Target,

(wider_1 <- select(fixed_1,Source,Target) |> 
    pivot_wider(names_from = "Source",
                names_repair = "minimal") )

  (wider_2 <- wider_1|> unnest_wider(col=true_sources,names_sep = "@"))

names(wider_2) <- gsub(pattern = "@.*",replacement = "",x=names(wider_2))

A reprex looks like this. It can be cut-and-pasted into a source pane to show exactly what is being worked with

d <- data.frame(
  source = rep("bow",10),
  target = rep("eye",10)
#>    source target
#> 1     bow    eye
#> 2     bow    eye
#> 3     bow    eye
#> 4     bow    eye
#> 5     bow    eye
#> 6     bow    eye
#> 7     bow    eye
#> 8     bow    eye
#> 9     bow    eye
#> 10    bow    eye
#>         V1  V2  V3  V4  V5  V6  V7  V8  V9 V10
#> source bow bow bow bow bow bow bow bow bow bow
#> target eye eye eye eye eye eye eye eye eye eye

Created on 2023-06-15 with reprex v2.0.2

For more complicated cases there is {tidyr} with pivot_longer() and pivot_wider(). For a quick and dirty, I prefer this.
See this, useful functions to convert wide to long and vice versa.

This topic was automatically closed 42 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.