1

I have a data-set that pulls the variables of interest but arranges them in rows when ideally they would be in separate columns. It looks like this

GEOID NAME VARIABLE VALUE 00601 ZCTA5 00601 PCT023003 17285 2 00601 ZCTA5 00601 PCT023004 572 3 00601 ZCTA5 00601 PCT023006 5 4 00601 ZCTA5 00601 P004001 18570 5 00602 ZCTA5 00602 PCT023003 35980 6 00602 ZCTA5 00602 PCT023004 2210 7 00602 ZCTA5 00602 PCT023006 22 8 00602 ZCTA5 00602 P004001 41520

and I'd like to have the 4 variables represent 4 columns all tied to the unique ZCTA5 value. How can i transform the data to fit that description. Sorry for poor wording.

medlearning
  • 143
  • 1
  • 2
  • 11

1 Answers1

1

We can use pivot_wider from tidyr

library(tidyr)
pivot_wider(df1, names_from = VARIABLE, values_from = VALUE)
# A tibble: 2 x 6
#  GEOID NAME        PCT023003 PCT023004 PCT023006 P004001
#  <int> <chr>           <int>     <int>     <int>   <int>
#1   601 ZCTA5 00601     17285       572         5   18570
#2   602 ZCTA5 00602     35980      2210        22   41520

data

df1 <- structure(list(GEOID = c(601L, 601L, 601L, 601L, 602L, 602L, 
602L, 602L), NAME = c("ZCTA5 00601", "ZCTA5 00601", "ZCTA5 00601", 
"ZCTA5 00601", "ZCTA5 00602", "ZCTA5 00602", "ZCTA5 00602", "ZCTA5 00602"
), VARIABLE = c("PCT023003", "PCT023004", "PCT023006", "P004001", 
"PCT023003", "PCT023004", "PCT023006", "P004001"), VALUE = c(17285L, 
572L, 5L, 18570L, 35980L, 2210L, 22L, 41520L)),
class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8"))
akrun
  • 874,273
  • 37
  • 540
  • 662