r - 复制数据框中的每一行的次数等于该行中的值出现在另一个数据框中的次数?
问题描述
我很抱歉,因为我不太确定如何在不让它变得非常冗长的情况下说出我的问题,因为重复的行还需要从原始行中更改一些值。
我有两个数据框。第一个,df1,记录了从源到目的地的所有实际路径,而第二个,df2,包含所有可能的路径。一些示例数据如下:
df1
排 | 资源 | 目的地 | 有效载荷 |
---|---|---|---|
1 | 一个 | 乙 | 10010101 |
2 | 一个 | D | 11101011 |
3 | 一个 | 乙 | 10111111 |
4 | 乙 | 乙 | 01100110 |
df2
排 | 资源 | 目的地 |
---|---|---|
1 | 一个 | 乙 |
2 | 乙 | 一个 |
3 | 乙 | C |
4 | 乙 | 乙 |
5 | 乙 | F |
6 | 一个 | D |
7 | D | 一个 |
8 | D | C |
9 | D | H |
对于我的数据,假设如果一个对象采用路径 A -> B 例如,它还采用源自 B 的所有可能路径,而不是原始源(想想网络集线器。以一种方式,并且每隔一段时间)。因此,由于我们有一个从 A -> B 的有效负载,我还需要记录从 B 到 C、E 和 F 的相同有效负载。我目前正在下面的 FOR 循环中完成此操作,但我想知道是否有更好的方法,最好是不使用循环的方法。我对 R 也有些陌生,因此即使对我的代码进行简单的更正也值得赞赏。
for (row in 1:dim(df1)[1]){
initialSource <- df1$source[row] #saves the initial source
paths <- df1[row,] #saves the current row for duplication
paths <- paths[rep(1, times = count(df2[df2$source %in% df1$destination[row], ])[[1]]), ] #duplicates the row
paths$source <- paths$destination #replaces the source values to be the location of the hub
paths$destination <- df2$destination[df2$source %in% paths$destination] #replaces the destination values to be every connection from the hub
paths <- paths[!(paths$destination %in% initialSource), ] #removes the row that would indicate data being sent back to the source
masterdf <- rbind(masterdf, paths) #saving the new data to a larger data frame that df1 is actually a sample of.
}
具有上述数据的第一个循环结束时的数据帧paths
如下所示:
排 | 资源 | 目的地 | 有效载荷 |
---|---|---|---|
1 | 乙 | C | 10010101 |
2 | 乙 | 乙 | 10010101 |
3 | 乙 | F | 10010101 |
解决方案
也许你可以尝试合并你的两个数据框。使用base R merge
,您可以执行以下操作(使用“Destination” fromdf1
和“Source” from df2
)。如您所述,您需要删除行以排除“原始来源”。重命名和选择列会为您提供最终输出。如果这是您的想法,请告诉我。
d <- subset(
merge(df1, df2, by.x = "Destination", by.y = "Source", all = TRUE),
Source != Destination.y
)
data.frame(
Source = d$Destination,
Destination = d$Destination.y,
Payload = d$Payload
)
输出
Source Destination Payload
1 B C 10010101
2 B E 10010101
3 B F 10010101
4 B C 10111111
5 B E 10111111
6 B F 10111111
7 B C 1100110
8 B F 1100110
9 B A 1100110
10 D C 11101011
11 D H 11101011
推荐阅读
- node.js - 来自 Firebase 功能的未经身份验证的响应状态
- reactjs - 在 React 端模拟电子东西
- c# - 过滤列表视图 c# wpf
- python - 减去特定的日期时间对象
- android - 将对象缓存到android中的文件(kotlin)
- php - 在 Wordpress 中集成 REST API
- arrays - WHERE IN 作为 Postgres 中的子查询
- r - 如何从闪亮应用程序中的 ggplot 中删除 NA 值?
- c++ - 如何将 wstringstream 和 getline 与 wchar_t 一起使用?
- android - Android Studio Build 后生成的代码保留在 build 文件夹中