[英]R multiply each row value of one dataframe with each row value of another, create new dataframe
[英]Comparing each row of one dataframe with a row in another dataframe using R
我是 R 的新手,我一直在寻找问题的答案,但没有找到。 我想比较两个数据框。
library(dplyr)
library(gtools)
v1 <- LETTERS[1:10]
combinations_from_4_letters <- (as.data.frame(combinations(n = 10, r = 4, v = v1),
stringsAsFactors = FALSE))
combinations_from_4_letters$group <- rep(1:15, each = 14)
combinations_from_2_letters <- (as.data.frame(combinations(n = 10, r = 2, v = v1),
stringsAsFactors = FALSE))
Dataframe 'combinations_from_4_letters' 包含可以由 10 个字母组成的所有组合,无需重复和排列。 这些组合被分为 1-15 组。 我想知道在每个组(基本上是频率表)中找到 10 个字母对(保存在 dataframe 'combinations_from_2_letters' 中)的频率。 我开始对两个数据帧进行一个复杂的循环,但我认为必须有一个更“R”的解决方案,类似于比较 dataframe 和一个向量,例如:
combinations_from_4_letters %in% combinations_from_2_letters[i,])
预先感谢您的帮助!
我推荐如下方法:
# adding dummy column for a complete cross-join
combinations_from_4_letters = combinations_from_4_letters %>%
mutate(ones = 1)
combinations_from_2_letters = combinations_from_2_letters %>%
mutate(ones = 1)
joined = combinations_from_2_letters %>%
inner_join(combinations_from_4_letters, by = "ones") %>%
# comparison goes here
mutate(within = ifelse(comb2 %in% comb4, 1, 0)) %>%
group_by(comb2) %>%
summarise(freq = sum(within))
您可能需要进行修改以确保它与确切的列名和您的比较条件相匹配。
关键思想:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.