矢量EdgeList都我有一個像向量:如何創建一個從R中
c("A", "B", "C", "D", "E", "F")
,我想創建一個像
"from" "to"
A B
B C
C D
D E
E F
一個數據幀我怎麼能做到呢?
矢量EdgeList都我有一個像向量:如何創建一個從R中
c("A", "B", "C", "D", "E", "F")
,我想創建一個像
"from" "to"
A B
B C
C D
D E
E F
一個數據幀我怎麼能做到呢?
另一種方式:
data.frame(from = vec[-length(vec)], to = vec[-1])
下面是使用一種方法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
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
我們也可以這樣做:
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
另一種方法是使用zoo
包,
library(zoo)
rollapply(vec, 2, by = 1, paste)
這就是爲什麼我喜歡這個網站。從來不知道「嵌入」。 – JasonAizkalns