home_wrecker
home_wrecker

Reputation: 375

swap elements between columns in the same row

I have a dataframe representing an edgelist for a graph as follows: | user1 | user2 | delta_t | |-------|-------|---------| | Bob | Alice | 10 | | Jake | June | -1 | I want to created a directed graph based on the timing of the interaction, and using igraph, an edge is always drawn from user1 to user2.
Therefore, I want to go through my dataframe, and rearrange the order of the nodes based on delta_t.

This is what I have right now:

network_edge_list <- transform(network_edge_list, user1 = ifelse(delta_t > 0, user2, user1), user2 = ifelse(delta_t > 0 , user1, user2))

It works fine BUT, every time it swaps the users in a row, it changes the name of user2 into a number. I am guessing this is because it has no way to keep track of the string value of user2 after the first swap, and so it makes an arbitrary replacement. Though happens consistently over the dataframe, and once a user is turned into a number, that number is correctly used throughout the dataframe, it is VERY annoying, and is making my next step much more difficult.

I also tried:

myfunction <- function(df){
   if (df[3] > 0){
     temp <- df[1]
     df[1] <- df[2]
     df[2] <- temp
   }
}
df <- apply(df, 1, function(x) myfunction) `

But I am not getting the results I was expecting, and is actually looking a lot more complicated than I was hoping it would be.

Anyone have any thoughts? Thanks

Upvotes: 1

Views: 98

Answers (2)

Ven Yao
Ven Yao

Reputation: 3710

df1 <- read.table(text="
user1 user2 delta_t
Bob Alice 10
Jake June -1", head=T, as.is=T)

df1 <- rbind(df1, df1)
df1
#   user1 user2 delta_t
# 1   Bob Alice      10
# 2  Jake  June      -1
# 3   Bob Alice      10
# 4  Jake  June      -1

df1[df1$delta_t>0, 1:2] <- df1[which(df1$delta_t>0), 2:1]
df1
#   user1 user2 delta_t
# 1 Alice   Bob      10
# 2  Jake  June      -1
# 3 Alice   Bob      10
# 4  Jake  June      -1

Upvotes: 0

cmbarbu
cmbarbu

Reputation: 4534

You are probably handing factors and it replaces the name by the number in the factor. You need to use as.character first on your columns.

network_edge_list$user1 <- as.character(network_edge_list$user1)
network_edge_list$user2 <- as.character(network_edge_list$user2)

Then your code should work just fine

Upvotes: 1

Related Questions