Bitanshu Das
Bitanshu Das

Reputation: 627

Altering the structure of a dataframe in R

I have a dataframe like the following

    Name  Salary  Company   Dept
     ABC   1000    xyz       pqr
     ABC2  1001    xyz       pqrs
     ABC3  1002    xyzt      pqrst

I want to reshape it so that it appears like

    Name  ABC
    Salary 1000
    Company xyz
    Dept   pqr
    Name   ABC2
    Salary  1001
    Company xyz
    Dept    pqr
    Name   ABC3
    Salary 1002
    Compant xyzt
    Dept   pqrst

Is it possible to do it in R? I want to then write each record in a excel file i.e. I want to have 3 excel files for details of ABC,ABC and ABC3.

Thank You

Upvotes: 0

Views: 41

Answers (2)

Andriy T.
Andriy T.

Reputation: 2030

If you want to create a ".csv" file for each table then you can achive it in a loop:

for (i in unique(data$Name)){

  write.csv(as.data.frame(t(data[data$Name == i, ])), file = paste0(i, ".csv")
            , row.names = T)

}

Alternatively use write.xlsx() from xlsx package

DATA:

data <- structure(list(Name = structure(1:3, .Label = c("ABC", "ABC2", 
"ABC3"), class = "factor"), Salary = 1000:1002, Company = structure(c(1L, 
1L, 2L), .Label = c("xyz", "xyzt"), class = "factor"), Dept = structure(1:3, .Label = c("pqr", 
"pqrs", "pqrst"), class = "factor")), .Names = c("Name", "Salary", 
"Company", "Dept"), class = "data.frame", row.names = c(NA, -3L
))

Upvotes: 1

Colonel Beauvel
Colonel Beauvel

Reputation: 31161

If you really want to do this and if df is your data.frame, you can do:

data.frame(names(df), c(t(as.matrix(df))))

Upvotes: 1

Related Questions