Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move columns of a data frame into rows after the first few columns?

Tags:

dataframe

r

I have a data frame with each row representing a sequence of schools

edu <- read.table(header=TRUE, text="Elem Mid High
e1 m1 h1
e2 m2 h2
e1 m2 h2
e3 m1 h1")

I'd like to transform this into a edge list

  s1 s2
1 e1 m1
2 e2 m2
3 e1 m2
4 e3 m1
5 m1 h1
6 m2 h2
7 m2 h2
8 m1 h1

for a directed graph (via the igraph package).

Here's how I do it:

e2m <- edu[,1:2]
m2h <- edu[,2:3]
colnames(e2m) <- c("s1", "s2")
colnames(m2h) <- c("s1", "s2")
schools <- rbind(e2m,m2e)

"schools" contains what I want, but it is iterative and becomes cumbersome if I want to add a fourth column (e.g. "Uni"). What is the vectorized way to do this?

like image 988
schnee Avatar asked Feb 12 '13 02:02

schnee


People also ask

How do I move data from columns to rows?

Here's how you can transpose cell content: Copy the cell range. Select the empty cells where you want to paste the transposed data. On the Home tab, click the Paste icon, and select Paste Transpose.

How do I move columns to rows in pandas?

Use the T attribute or the transpose() method to swap (= transpose) the rows and columns of pandas. DataFrame . Neither method changes the original object but returns a new object with the rows and columns swapped (= transposed object).


1 Answers

Here is a possible solution:

len <- seq_along(edu)
a <- head(len, -1)
b <- tail(len, -1)

data.frame(s1=as.character(unlist(edu[, a])), s2=as.character(unlist(edu[, b])))
like image 59
Tyler Rinker Avatar answered Sep 29 '22 17:09

Tyler Rinker