jane
jane

Reputation: 567

Rotate a dataframe with header

How can we change or rotate the dataframe to be like the example below (First line represents a header)?

State1 Customer1 State2 Customer2 State3 Customer3 State4 Customer4
Us     1980      FR     274       DE     641       UK     521

Script:

State <- c("US", "FR","DE", "UK")
Customer <- c(1980, 274, 641, 521)

Table <- data.frame(State, Customer)

Upvotes: 4

Views: 75

Answers (3)

chinsoon12
chinsoon12

Reputation: 25225

An option using data.table:

library(data.table)
DT <- fread("State1 Customer1 State2 Customer2 State3 Customer3 State4 Customer4
Us     1980      FR     274       DE     641       UK     521")
melt(DT, measure.vars=patterns("State", "Customer"), value.name=c("State","Customer"))[, 
    variable := NULL][]

output:

   State Customer
1:    Us     1980
2:    FR      274
3:    DE      641
4:    UK      521

Upvotes: 1

Darren Tsai
Darren Tsai

Reputation: 35594

A base way

df <- cbind.data.frame(split(Table, 1:nrow(Table)))
names(df) <- sub("(\\d+)\\.(\\D+)", "\\2\\1", names(df))

#   State1 Customer1 State2 Customer2 State3 Customer3 State4 Customer4
# 1     US      1980     FR       274     DE       641     UK       521

Another choice to use purrr::imap_dfc

library(purrr)
imap_dfc(split(Table, 1:nrow(Table)), ~ set_names(.x, paste0, .y))

#   State1 Customer1 State2 Customer2 State3 Customer3 State4 Customer4
# 1     US      1980     FR       274     DE       641     UK       521

Data

Table <- structure(list(State = structure(c(4L, 2L, 1L, 3L), .Label = c("DE", 
"FR", "UK", "US"), class = "factor"), Customer = c(1980, 274, 
641, 521)), class = "data.frame", row.names = c(NA, -4L))

Upvotes: 2

NelsonGon
NelsonGon

Reputation: 13319

With just base:

  res<-read.table(text=paste0(State," ",Customer,collapse=" "),sep=" ")
  names(res)[seq(1,ncol(res),2)] <- paste0("state",1:4)
 names(res)[-seq(1,ncol(res),2)] <-paste0("customer_",1:4)

Result:

 res
      state1 customer_1 state2 customer_2 state3 customer_3 state4 customer_4
    1     US       1980     FR        274     DE        641     UK        521

Upvotes: 1

Related Questions