David Chris
David Chris

Reputation: 255

How to display the dataframe in a particular format in R

I need your help/suggestions to display a data frame in R in a particular format. Kindly find the demo dataset below.

d <-
data.frame(
year = c(1995, 1995, 1995, 1996, 1996, 1996, 1997, 1997, 1997),
Product_Name = c(
  "Table",
  "Chair",
  "Bed",
  "Table",
  "Chair",
  "Bed",
  "Table",
  "Chair",
  "Bed"
),
Product_desc = c("X", "X", "X", "Y", "Y", "Y", "Z", "Z", "Z"),
Cost = c(1, 2, 3, 4, 2, 3, 4, 5, 6)
)

The dataframe is getting displayed in this format.

   Product_Name Product_desc  year  Cost
   Table        X             1995     1
   Chair        X             1995     2
   Bed          X             1995     3
   Table        Y             1996     4
   Chair        Y             1996     2
   Bed          Y             1996     3
   Table        Z             1997     4
   Chair        Z             1997     5
   Bed          Z             1997     6

I want the dataframe to be displayed in this format.

   Product_Name Product_desc  year  Cost
   Table        X             1995     1
   Table        Y             1996     4
   Table        Z             1997     4
   Chair        X             1995     2
   Chair        Y             1996     2
   Chair        Z             1997     5
   Bed          X             1995     3
   Bed          Y             1996     3
   Bed          Z             1997     6

I am not able to display it this way. The biggest issue/Challenge which I am facing is with respect to the column year. I dont know how to make my year get displayed same as the above format.

Kindly let me know your suggestions.

Thanks in Advance.

David

Upvotes: 3

Views: 418

Answers (2)

Adamm
Adamm

Reputation: 2306

I didn't check the output, hope it's correct.

df <- df[with(df, order(rev(Product_Name))), ]
df <- data.table::setcolorder(df, c('Product_Name', 'Product_desc',  'year',  'Cost'))

Upvotes: 4

fmarm
fmarm

Reputation: 4284

If I understand correctly, you want to sort the rows by descending Product_name, ascending Product_desc, and reorder the columns. This is a way to do this

library(dplyr)

d %>% arrange(desc(Product_Name),Product_desc) %>% 
      select(Product_Name,Product_desc,year,Cost)

Upvotes: 4

Related Questions