【发布时间】:2018-10-15 12:42:05
【问题描述】:
我想生成一个data.frame 的边。当许多边在一个节点上结束时,就会出现问题。边在向量from 和to 中定义。
# Data
vertices <- data.frame(id = 1:3, label = c("a", "b", "c"), stringsAsFactors = FALSE)
to <- c("a", "b", "c")
from1 <- c("c", "a", "b")
from2 <- c("c", "a", "a,b,c")
我尝试了什么:
# Attempt 1
create_edges_1 <- function(from, to) {
to <- sapply(to, function(x){vertices$id[vertices$label == x]})
from <- sapply(from, function(x){vertices$id[vertices$label == x]})
data.frame(from = from, to = to, stringsAsFactors = FALSE)
}
这适用于例如create_edges_1(from1, to),输出为:
from to
c 3 1
a 1 2
b 2 3
但是,例如from2,此尝试失败。
所以我尝试了以下方法:
# Attempt 2
create_edges_2 <- function(from, to) {
to <- sapply(unlist(sapply(strsplit(to, ","), function(x){vertices$id[vertices$label == x]})), function(x){rep(x, sapply(strsplit(from2, ","), length))})
from <- unlist(sapply(strsplit(from2, ","), function(x){vertices$id[vertices$label == x]}))
data.frame(from = from, to = to, stringsAsFactors = FALSE)
}
这个想法是为不止一条边结束的每个节点“拉伸”to。但是create_edges_2(from1, to) 和create_edges_2(from2, to) 都会抛出错误
rep(x, sapply(strsplit(from2, ","), length)) 中的错误: 'times' 参数无效
我在sapply 语句中做错了什么?
create_edges_2(from2, to) 的预期输出是:
from to
3 1
1 2
1 3
2 3
3 3
【问题讨论】: