如何从数据集中创建双向表?转置一排?

时间:2014-09-28 17:41:50

标签: r

我有以下数据框。

Foo    Gender    Binary    Zip    Frequency
1      Male      0         Yes    4
3      Female    1         No     6
1      Female    0         No     7
2      Male      0         Yes    1
2      Male      0         No     3

如何将Foo转换为Row变量并将其余变量保留为列?我希望输出看起来像这样:

    Gender    Binary    Zip    Frequency
Foo
1    Male       0       Yes        4
     Female     0       No         7
2    Male       0       Yes        1
     Male       0       No         3
3    Female     1       No         6

我知道转置功能,但我认为它适用于整个矩阵或数据帧。有没有办法转置单个列,以便它是一个行变量?我也知道重塑和dcast,但我不知道如何获得它,使它看起来像上面那个。

>> dput(head(df1))
>> c(0, 0, 35, 0, 0, 0)

2 个答案:

答案 0 :(得分:3)

我真的不明白你想做什么。对我来说,你只需要根据Foo列对表进行排序,然后删除重复的智能打印值。

xx <- dat[order(dat$Foo),]
xx$Foo[duplicated(xx$Foo)] <- ""

Foo Gender Binary Zip Frequency
A 1   Male   0      Yes 4        
C     Female 0      No  7        
D 2   Male   0      Yes 1        
E     Male   0      No  3        
B 3   Female 1      No  6   

编辑:

如果你有一个表对象,你不能使用$ operator,你应[进行子集化

## you should use as.table to get good formatting
xx <- as.table(xx[order(xx[,"Foo"]),])
xx[duplicated(xx[,"Foo"]),"Foo"] <- ""
xx
  Foo Gender Binary Zip Frequency
1   1   Male      0 Yes         4
3     Female      0  No         7
4   2   Male      0 Yes         1
5       Male      0  No         3
2   3 Female      1  No         6

其中xx是:

structure(c("1", "3", "1", "2", "2", "Male", "Female", "Female", 
"Male", "Male", "0", "1", "0", "0", "0", "Yes", "No", "No", "Yes", 
"No", "4", "6", "7", "1", "3"), .Dim = c(5L, 5L), .Dimnames = list(
    c("A", "B", "C", "D", "E"), c("Foo", "Gender", "Binary", 
    "Zip", "Frequency")), class = "table")

答案 1 :(得分:2)

看到预期的结果,我做了以下几点。 mydf是您的样本数据。

library(dplyr)

mydf %>%
    arrange(Foo) %>%
    group_by(Foo) %>%
    mutate(new = row_number(Foo)) %>%
    ungroup() %>%
    mutate(Foo = ifelse(new != 1, "", Foo)) %>%
    select(-new)

Source: local data frame [5 x 5]

  Foo Gender Binary Zip Frequency
1   1   Male      0 Yes         4
2     Female      0  No         7
3   2   Male      0 Yes         1
4       Male      0  No         3
5   3 Female      1  No         6