R 一个数据帧行与另一个数据帧行的频率
有人能帮我如何从另一个数据帧计数吗 df1(输出) df2(tempdf)R 一个数据帧行与另一个数据帧行的频率,r,R,有人能帮我如何从另一个数据帧计数吗 df1(输出) df2(tempdf) 我想从df2中计算df1的项目、LC、财政月的频率您可以使用表进行计数,并使用因子将df1与df2合并,并且在使用多个列进行合并时,您需要交互 table(factor(interaction(df2[c("Item","LC","Fiscal.Month")]), levels=interaction(df1))) #0S1576.MW92.2019-M06 0S1576.MW92.2019-M07 0S1576.OY
我想从df2中计算df1的项目、LC、财政月的频率您可以使用
表进行计数,并使用因子将df1
与df2
合并,并且在使用多个列进行合并时,您需要交互
table(factor(interaction(df2[c("Item","LC","Fiscal.Month")]), levels=interaction(df1)))
#0S1576.MW92.2019-M06 0S1576.MW92.2019-M07 0S1576.OY01.2019-M06
# 2 1 3
#0S1576.OY01.2019-M07 0S1576.OY01.2019-M08 0S1576.OY01.2019-M09
# 0 0 0
#0S1576.RM11.2019-M06 0S1576.RM11.2019-M07 0S1576.RM11.2019-M08
# 3 0 0
或者使用匹配
和制表
的速度改进版:
(df1$freq <- tabulate(match(interaction(df2[c("Item","LC","Fiscal.Month")]), interaction(df1)), nrow(df1)))
#[1] 2 1 3 0 0 0 3 0 0
我可以将其存储在数据框而不是表中吗??
table(factor(interaction(df2[c("Item","LC","Fiscal.Month")]), levels=interaction(df1)))
#0S1576.MW92.2019-M06 0S1576.MW92.2019-M07 0S1576.OY01.2019-M06
# 2 1 3
#0S1576.OY01.2019-M07 0S1576.OY01.2019-M08 0S1576.OY01.2019-M09
# 0 0 0
#0S1576.RM11.2019-M06 0S1576.RM11.2019-M07 0S1576.RM11.2019-M08
# 3 0 0
(df1$freq <- tabulate(match(interaction(df2[c("Item","LC","Fiscal.Month")]), interaction(df1)), nrow(df1)))
#[1] 2 1 3 0 0 0 3 0 0
library(fastmatch)
df1$freq <- tabulate(fmatch(interaction(df2[c("Item","LC","Fiscal.Month")]), interaction(df1)), nrow(df1))