1

I currently have a data frame in r that looks like an extended version of this:

   Var Result Location
1  A   0.10       FL
2  B     NA       FL
3  C   2.50       FL
4  D     NA       FL
5  E     NA       FL
6  A   0.45       GA
7  B     NA       GA
8  C     NA       GA
9  D   2.20       GA
10 E   0.13       GA

I am trying to have the 'var' column be the header and the data associated with each value below it in rows. Is there an efficient way to achieve this goal? Due to the repetition of the variables I have been unsuccessful just transcribing the table. Maybe this is an issue on my part.

Cbotelho
  • 87
  • 5
  • 1
    The word you are using to describe the process is a conflation of the proper term "transpose". In your case it would not be a good idea to do this because there is a mixture of column classes: numeric and character. If you transposed that dataframe (which is certainly possible with the `t` function), you would coerce all the numeric values to character and thereby inhibit proper availability of numeric data. The only situation where this might be useful would be in preparation for display of values. The solution offered by ViniciusFelix gets around this by a more complete rearrangement. – IRTFM Oct 08 '21 at 17:40
  • Does this answer your question? [How to reshape data from long to wide format](https://stackoverflow.com/questions/5890584/how-to-reshape-data-from-long-to-wide-format) – maydin Oct 08 '21 at 17:45

2 Answers2

3

-- libraries

library(tidyr)
library(dplyr)

-- code

df %>% 
  pivot_wider(names_from = Var,values_from = Result)

-- output

# A tibble: 2 x 6
  Location     A     B     C     D     E
  <chr>    <dbl> <dbl> <dbl> <dbl> <dbl>
1 FL        0.1     NA   2.5  NA   NA   
2 GA        0.45    NA  NA     2.2  0.13

-- data

df <-structure(list(Var = c("A", "B", "C", "D", "E", "A", "B", "C","D", "E"), Result = c(0.1, NA, 2.5, NA, NA, 0.45, NA, NA, 2.2,0.13), Location = c("FL", "FL", "FL", "FL", "FL", "GA", "GA",                       "GA", "GA", "GA")), class = "data.frame", row.names = c(NA, -10L))
Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32
  • This worked with my dataset. I couldn't get it to work in one function, but I was able to split into the separate variables, use this method to transpose it, and recombine the data into one table. – Cbotelho Oct 15 '21 at 16:01
2

Using xtabs from base R

xtabs(Result ~ Location + Var, df)
        Var
Location    A    C    D    E
      FL 0.10 2.50 0.00 0.00
      GA 0.45 0.00 2.20 0.13

data

df <- structure(list(Var = c("A", "B", "C", "D", "E", "A", "B", "C", 
"D", "E"), Result = c(0.1, NA, 2.5, NA, NA, 0.45, NA, NA, 2.2, 
0.13), Location = c("FL", "FL", "FL", "FL", "FL", "GA", "GA", 
"GA", "GA", "GA")), class = "data.frame", row.names = c(NA, -10L
))
akrun
  • 874,273
  • 37
  • 540
  • 662