如何在R中从vector创建edgelist

时间:2016-07-07 13:29:53

标签: r

我有一个像:

这样的矢量
void Application_BeginRequest(object sender, EventArgs e) 

我希望创建一个像

这样的数据框
c("A", "B", "C", "D", "E", "F")

我该如何实现?

5 个答案:

答案 0 :(得分:4)

另一种方式:

data.frame(from = vec[-length(vec)], to = vec[-1])

答案 1 :(得分:2)

以下是一种使用embed并重新排列列的方法:

# data
temp <- c("A", "B", "C", "D", "E", "F")

embed(temp, 2)[, c(2,1)]

     [,1] [,2]
[1,] "A"  "B" 
[2,] "B"  "C" 
[3,] "C"  "D" 
[4,] "D"  "E" 
[5,] "E"  "F"

将其放入data.frame中,将其包装在data.frame:

setNames(data.frame(embed(temp, 2)[, c(2,1)]), c("from", "to"))
  from to
1    A  B
2    B  C
3    C  D
4    D  E
5    E  F

答案 2 :(得分:2)

na.omit(data.frame(from = vec, to = dplyr::lead(vec)))
  from to
1    A  B
2    B  C
3    C  D
4    D  E
5    E  F

答案 3 :(得分:2)

另一种方法是使用zoo包,

library(zoo)
rollapply(vec, 2, by = 1, paste)

答案 4 :(得分:0)

我们也可以这样做:

vec <- c("A", "B", "C", "D", "E", "F")
x <- rep(seq(length(vec)), each=2)[-length(vec)*2][-1]
# [1] 1 2 2 3 3 4 4 5 5 6
data.frame(matrix(vec[x], ncol = 2, byrow = T))

或者:

data.frame(t(sapply(seq(length(vec)-1), function(i) c(vec[i], vec[i+1]))))

  # X1 X2
# 1  A  B
# 2  B  C
# 3  C  D
# 4  D  E
# 5  E  F