Home > OS >  How can I flip a dataframe in R
How can I flip a dataframe in R

Time:10-09

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.

CodePudding user response:

-- 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))

CodePudding user response:

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
))
  •  Tags:  
  • r
  • Related