0

I'm new in R coding. I would like tyo do a specific transpose. I know that function "t()" will do the job it was natural transpose.

My input dataframe is :

policyID   statecode    county          var1       var2         var3
119736       FL        CLAY COUNTY     498960     498960       498960
448094       FL        CLAY COUNTY     132237     132230       132235
206893       FL        CLAY COUNTY     190745     190758       19072
333743       FL        CLAY COUNTY       0        79520          0

What I want to do is transpose my dataframe keeping policyID, statecode and county like columns.

output schema :

policyID    statecode   county  Name    Value
119736  FL  CLAY COUNTY var1    498960
119736  FL  CLAY COUNTY var2    498960
119736  FL  CLAY COUNTY var3    498960
448094  FL  CLAY COUNTY var1    132237
448094  FL  CLAY COUNTY var2    132230
448094  FL  CLAY COUNTY var3    132235
206893  FL  CLAY COUNTY var1    190745
206893  FL  CLAY COUNTY var2    190758
206893  FL  CLAY COUNTY var3    19072
333743  FL  CLAY COUNTY var1    0
333743  FL  CLAY COUNTY var2    79520
333743  FL  CLAY COUNTY var3    0

Does somebody could help me?? Notice that, input dataset is just a sample. The real dataset contains ~200 columns ans I always want to keep policyID, statecode and county like columns.

thanks.

Shakile
  • 343
  • 2
  • 5
  • 13
  • 3
    Sounds like a wide to long conversion. Do you mean something like `library(tidyverse); df %>% gather(key, value, -var1, -var2, -var3)`? If not please provide your expected output for the sample data you give. – Maurits Evers Jun 11 '18 at 12:42
  • Your expected output makes no sense to me. What do you hope to store in the `x`s? – Maurits Evers Jun 11 '18 at 22:15
  • Hello Maurits, I modified my post adding an example of input dataset and output. thanks for your help. – Shakile Jun 12 '18 at 11:57
  • Ok, so you're after a simple wide-to-long conversion; in your case, this is simply a modified version of what I said in my first comment: `library(tidyverse); df.out <- df %>% gather(Name, Value, starts_with("var"))`, where `df` is the source `data.frame`. – Maurits Evers Jun 12 '18 at 13:02

1 Answers1

-1

I agree with Maurits, sounds like wide to long to wide (modified). Instead of tidyverse as mentioned also reshape2::melt and reshape2::cast are possible solutions. Peter

Peter Hahn
  • 148
  • 8