在R中:我想检查df1$A的一个值在df2$A中有多少次

  • 本文关键字:一个 多少次 df2 df1 r dataframe
  • 更新时间 :
  • 英文 :


我有两个数据帧。

df1 
A B
1 x
2 x
3 x
4 x
5 x
6 x
7 x
And df2
A 
1
1
1
2
2
1
5

不是,我想检查df1$A的一个值在df2$A中有多少次。输出应该是这样的:

1  4 (times)
2  2
3  0 
4  0
5  1
6  0
7  0

假设你有df1和df2,我们可以在基R中这样做来解决这个问题。为此,我们必须对df1$A中的每个值进行迭代,然后将它们与df2$A的值进行匹配。因此,这是一个相当手动的过程,但没有办法绕过这个过程。

# Find the unique values in df1$A. 
# In case we have the same value twice in df1, we don't want to match twice.
values_1 <- unique(df1$A)
# To merge the result we need the indices of our unique values in df1$A.
positions <- match(values_1, df1$A)
# Count the number of times the specific value is in df2
count <- sapply(values_1, function(x) sum(x == df2$A) )
# Add a new column to df1, using the positions for indexing.
df1$count <- count[positions]

这产生了预期的结果

df1
## Output ##
#   A count
# 1 1     4
# 2 2     2
# 3 3     0
# 4 4     0
# 5 5     1
# 6 6     0
# 7 7     0

编辑:备选(更快(答案:

在给出上述解决方案之后,我想到的一个替代方案是";预制表";3的数据和与CCD_ 4的匹配。在来自df1$A的值与df2$A中的值密切相关的情况下,这对于大型数据集将快得多,因为df2$A不包括df1$A中不存在的大的唯一值集(非唯一计数(。

这个想法有点类似,但更改了代码的后半部分。

# Find the unique values in df1$A. 
# In case we have the same value twice in df1, we don't want to match twice.
values_1 <- unique(df1$A)
# To merge the result we need the indices of our unique values in df1$A.
positions <- match(values_1, df1$A)
# Count number of unique values in df2$A
count <- table(df2$A)
# match values_1 to the names of count, and insert these values into df1$count
df1$count <- count[match(values_1, names(count))][positions]

这给出了类似的结果,但是用NA_integer_代替0的值。

请注意,通过使用table函数的替代方案,第二种方法可以更快地完成,CCD_11不会将我们的值转换为因子,因为因子通常非常慢。

相关内容

最新更新