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?
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.
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).
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])))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With