R-比较数据框列中的所有元素与跨所有列的另一数据框中一行的元素 [英] R - Compare all elements in a dataframe column with an element in a row in another dataframe, across all columns

查看:67
本文介绍了R-比较数据框列中的所有元素与跨所有列的另一数据框中一行的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例数据:

df1 = data.frame('A' = seq(1,10), 'B' = seq(11,20), 'C' = seq(21,30))
df1
#     A  B  C
# 1   1 11 21
# 2   2 12 22
# 3   3 13 23
# 4   4 14 24
# 5   5 15 25
# 6   6 16 26
# 7   7 17 27
# 8   8 18 28
# 9   9 19 29
# 10 10 20 30

df2 = data.frame('A'=quantile(df1$A, probs=c(0.25,0.5,0.75)),
                 'B'=quantile(df1$B, probs=c(0.25,0.5,0.75)),
                 'C'=quantile(df1$C, probs=c(0.25,0.5,0.75)))
df2
#        A     B     C
# 25% 3.25 13.25 23.25
# 50% 5.50 15.50 25.50
# 75% 7.75 17.75 27.75

df3 = data.frame('A'=c(5,8,6,2,1), 'B'=c(11,12,13,19,20), 'C'=c(21,27,24,26,25))
df3
#   A  B  C
# 1 5 11 21
# 2 8 12 27
# 3 6 13 24
# 4 2 19 26
# 5 1 20 25

所需结果:

#     A B C
# Q1  3 2 4
# Med 2 2 2
# Q3  1 2 0

我想获取df3每列中没有的元素

I want to get the no of elements in each column of df3 that are


  • i)< df2 ['25%,] (也是此行中的< > 其他)

  • ii)> df2 ['50%',]

  • iii)> df2 ['75%',]

  • i) < df2['25%,] (also this, < in this row, > in others)
  • ii) > df2['50%',]
  • iii) > df2['75%',]

这些结果将作为单独的数据帧显示在3行中。 / em>

These results to be displayed in 3 rows as separate dataframe.

推荐答案

您可以在<$ c中使用 sapply $ c> mapply 调用:

You can use sapply in a mapply call :

mapply(function(x, y) colSums(sapply(x, `<`, y)), df2, df3)

#     A B C
#[1,] 3 2 4
#[2,] 2 2 2
#[3,] 1 2 0

这篇关于R-比较数据框列中的所有元素与跨所有列的另一数据框中一行的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆