首页 > 解决方案 > 复制数据框中的每一行的次数等于该行中的值出现在另一个数据框中的次数?

问题描述

我很抱歉,因为我不太确定如何在不让它变得非常冗长的情况下说出我的问题,因为重复的行还需要从原始行中更改一些值。

我有两个数据框。第一个,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

标签: rdataframe

解决方案


也许你可以尝试合并你的两个数据框。使用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

推荐阅读