r - 在行之间应用函数,按变量分组,计算其他列中变量之间的所有可能组合

标签 r dataframe

我在 R 中有一个大的 data.frame,它的简化版本看起来像这样(真实的 data.frame 在“颜色”列中有 20 种颜色,在“数字”列中有 10 个不同的数字:

Color   Number  Y
blue    1       5
blue    2       3
blue    3       2
red     1       5
red     2       8
red     3       2
green   1       2
green   2       9
green   3       3

对于“颜色”中的每种颜色,我想通过比较“Y”列的相应值,在“数字”列中的所有数字组合之间应用一个函数。让我们以一个简单的函数为例:
if x >= y, print 1, else print 0 # where x and y represent the first and second values to be compared, respectively 

我将其作为输出 data.frame 获得:
Color   Comparison  Y
blue    1_vs_2      1
blue    1_vs_3      1
blue    2_vs_1      0
blue    2_vs_3      1
blue    3_vs_1      0
blue    3_vs_2      0
red     1_vs_2      0
red     1_vs_3      1
red     2_vs_1      1
red     2_vs_3      1
red     3_vs_1      0
red     3_vs_2      0
green   1_vs_2      0
green   1_vs_3      0
green   2_vs_1      1
green   2_vs_3      1
green   3_vs_1      1
green   3_vs_2      0

最佳答案

使用 dplyr :

df <- data.frame(Color = c(rep("blue",3), rep("red", 3), rep("green", 3)),
                     Number = rep(1:3, 3),
                     Y = c(5,3,2,5,8,2,2,9,3))

df %>% 
  left_join(df, by = c("Color")) %>% 
  filter(Number.x != Number.y) %>% 
  mutate(Comparison = sprintf("%s_vs_%s", Number.x, Number.y))  %>% 
  mutate(Y = ifelse(Y.x - Y.y >= 0, 1, 0)) %>% 
  select(Color, Comparison, Y)

   Color Comparison Y
1   blue     1_vs_2 1
2   blue     1_vs_3 1
3   blue     2_vs_1 0
4   blue     2_vs_3 1
5   blue     3_vs_1 0
6   blue     3_vs_2 0
7    red     1_vs_2 0
8    red     1_vs_3 1
9    red     2_vs_1 1
10   red     2_vs_3 1
11   red     3_vs_1 0
12   red     3_vs_2 0
13 green     1_vs_2 0
14 green     1_vs_3 0
15 green     2_vs_1 1
16 green     2_vs_3 1
17 green     3_vs_1 1
18 green     3_vs_2 0

关于r - 在行之间应用函数,按变量分组,计算其他列中变量之间的所有可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42444590/

相关文章:

r - 使用 formatC 将 0 添加到 arg 中的序列中,在 R 中返回错误

r - 达到阈值时 dplyr 重置计数器

python - 通过 Pandas 在 Python 中计算和粘贴每个团队的目标数量滚动平均值

scala - Spark 计数大量列

python - 充满字符串的数据框(带有一些空字符串);想要将一些列转换为整数,一些列转换为 float ,并将一些保留为字符串

arrays - 如何存储在多重图中使用的 ggplots 列表而不覆盖以前的图?

r - 使用 ggridges 可视化泊松随机样本组

r - 从 R 对象中提取信息并将其导入模型汇总表

python - 如何使用多个条件更新列,并从另一列中获取相应的值 Python Pandas

python - 获取给定列中使用的唯一字符列表