Grazy_Cirl
Grazy_Cirl

Reputation: 21

Manipulation on rows and columns of a dataset

Sample Input dataset

   x  y  z
a  1  2 3
b  4  5 6
c  7  8 9

where a,b,c are rownames. x,y,z are column names.

I want output to be like this:

         cell   Value
         a_x      1
         b_x      4
         c_x      7
         a_y      2
         b_y      5
         c_y      8
         a_z      3
         b_z      6
         c_z      9

where cell and value are the 2 columns. How do we do this? I am new to R.

Upvotes: 1

Views: 467

Answers (2)

Julián Urbano
Julián Urbano

Reputation: 8488

Sample data:

> d<-data.frame(x=1:3,y=4:6,z=7:9)*10
> d
   x  y  z
1 10 40 70
2 20 50 80
3 30 60 90

You can stack your data frame, but you would still miss the row names:

> s<-stack(d)
  values ind
1     10   x
2     20   x
3     30   x
4     40   y
5     50   y
6     60   y
7     70   z
8     80   z
9     90   z

So append row names to column names:

> s$ind<-paste(s$ind,rownames(d),sep="_")
> s
  values ind
1     10 x_1
2     20 x_2
3     30 x_3
4     40 y_1
5     50 y_2
6     60 y_3
7     70 z_1
8     80 z_2
9     90 z_3

Upvotes: 1

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

This should get you close enough: Treat your data.frame as a table and make use of the data.frame method for table to get this long form. Use paste if you really want to combine "Var1" and "Var2".

data.frame(as.table(as.matrix(mydf)))
#   Var1 Var2 Freq
# 1    a    x    1
# 2    b    x    4
# 3    c    x    7
# 4    a    y    2
# 5    b    y    5
# 6    c    y    8
# 7    a    z    3
# 8    b    z    6
# 9    c    z    9

Of course, if your data are already class "table", then just use data.frame(<YourData>).

Upvotes: 2

Related Questions