改变R中数据帧的结构

时间:2015-07-22 08:53:53

标签: r dataframe

我有一个类似以下的数据框

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

我想重新塑造它,使它看起来像

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

是否可以在R中进行? 我想在excel文件中写下每条记录,即我想要有3个excel文件,以获取ABC,ABC和ABC3的详细信息。

谢谢

2 个答案:

答案 0 :(得分:1)

如果你真的想这样做而df是你的data.frame,你可以这样做:

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

答案 1 :(得分:1)

如果你想创建一个" .csv"每个表的文件,然后你可以循环实现它:

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

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

}

或者使用write.xlsx()

中的xlsx

数据

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