“较长的物体长度不是较短的物体长度的倍数”。 [英] "longer object length is not a multiple of shorter object length"

查看:211
本文介绍了“较长的物体长度不是较短的物体长度的倍数”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此数据集-

print(df)

  object    group   
1 apple      A    
1 banana     B    
1 pear       A    
1 robot      C

print(df2)

  object    group   
1 apple      A    
1 apple      B    
1 apple      A    
1 robot      C
1 robot      C
1 robot      C
1 banana     C

我想计算每个值出现在另一个数据集中的次数,该次数看起来​​完全一样,但是绘制来自不同时间段的数据。另一个数据集称为 df2

I'd like to count the number of times each value shows up in another data set, which looks exactly the same but draws data from a different time period. The other dataset is called df2.

我使用了此代码-

x <- df %>%
  mutate(reference = length(df2[df2$object == object,]$object))

它给了我这个错误:较长的对象长度不是较短的对象长度的倍数

It gave me this error: longer object length is not a multiple of shorter object length.

当我在dplyr之外运行它时,它可以正常工作-

It works when I run this outside of dplyr, like this -

object <- "apple"
length(df2[df2$object == object,]$object)

我可以做这样的相对引用吗,在过滤器中包含 object 吗?

Can I do a relative reference like that, including object in the filter?

推荐答案

根据我的评论:dplyr函数在作为矢量的整个列上工作。尝试

From my comment: dplyr functions work on the whole column taken as a vector. Try

df %>%
rowwise() %>% 
mutate(reference = length(df2[df2$object == object,]$object))%>%
ungroup()

如您所说,除非您计划进行进一步的逐行操作,否则将需要 ungroup

As you said, ungroup will be needed, unless you plan on doing further row-wise operations.

这篇关于“较长的物体长度不是较短的物体长度的倍数”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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