sta*_*oob 7 r graph cluster-analysis dynamic-programming igraph
我正在使用 R 编程语言。
假设有 100 人 - 每个人都用 1:100 开始的 ID 表示。每个人都可以与其他人成为朋友。数据集可以用图形/网络格式表示,如下所示:
# Set the seed for reproducibility
set.seed(123)
# Generate a vector of ID's from 1 to 100
ids <- 1:100
# Initialize an empty data frame to store the "from" and "to" values
edges <- data.frame(from=integer(), to=integer(), stringsAsFactors=FALSE)
# Iterate through the ID's
for(id in ids) {
# Randomly select a minimum of 1 and a maximum of 8 neighbors for the current ID
neighbors <- sample(ids[ids != id], size=sample(1:8, size=1))
# Add a new row to the data frame for each "to" value
for(neighbor in neighbors) {
edges <- rbind(edges, data.frame(from=id, to=neighbor))
}
}
Run Code Online (Sandbox Code Playgroud)
正如我们所看到的,数据可以可视化以揭示图形/网络格式:
library(igraph)
library(visNetwork)
# Convert the data frame to an igraph object
g <- graph_from_data_frame(edges, directed=FALSE)
# Plot the graph
plot(g)
# Optional visualization
#visIgraph(g)
Run Code Online (Sandbox Code Playgroud)
现在,假设该数据集中的每个人都有一定数量的 cookie。这看起来像这样:
set.seed(123)
cookies = data.frame(id = 1:100, number_of_cookies = c(abs(as.integer(rnorm(25, 15, 5))), abs(as.integer(rnorm(75, 5, 5)))))
Run Code Online (Sandbox Code Playgroud)
这是我的问题:
我编写了一个函数,它接受一个 ID 作为输入,然后返回该 ID 以及该 ID 的所有邻居的 cookie 总数:
library(data.table)
library(dplyr)
sum_cookies_for_id <- function(id) {
# Get the connected IDs for the given ID
connected_ids <- c(id, edges[edges$from == id | edges$to == id, "to"])
# Sum the number of cookies for all connected IDs
sum(cookies[cookies$id %in% connected_ids, "number_of_cookies"])
}
# Test the function
sum_cookies_for_id(23)
Run Code Online (Sandbox Code Playgroud)
但除此之外,我不知道如何继续。
有人可以告诉我如何继续为这个问题编写代码吗?在这样的例子中可以使用动态规划吗?
谢谢!
注意事项:
| 归档时间: |
|
| 查看次数: |
289 次 |
| 最近记录: |