首页 > 解决方案 > R:在数据框中获取匹配表情符号对的频率时遇到问题

问题描述

我在获取 R 中类似表情符号对的频率时遇到问题。我不知道是否存在逻辑错误。我的代码段如下所示:

emoji_pouch <- c("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "")
emo_mat <- matrix(emoji_pouch, ncol = 2, byrow = T)
emo_mat
#     [,1] [,2]
#[1,] ""  "" 
#[2,] ""  "" 
#[3,] ""  "" 
#[4,] ""  "" 
#[5,] ""  "" 
#[6,] "" "" 
#[7,] ""  "" 
#[8,] ""  "" 
#[9,] ""  "" 
#[10,] ""  "" 
#[11,] ""  "" 

links <- data.frame(source= emo_mat[,1], target= emo_mat[,2])

weight_col_count <- c()

#Possible logic error which I can't find
for(i in 1:nrow(links))
{
  weight_counter <- 1
  
  for(j in 1: nrow(links))
  {
    if(links[i, ] == links[j, ]) #I am not sure if I doing this line correctly??
    {
      weight_counter <- weight_counter + 1
    }
  }

  weight_col_count[i] <- weight_counter
}

links$weight <- weight_col_count
links 

# gives me output like this:
#   source target weight
#1                   2
#2                   2
#3                   5
#4                   5
#5                   5
#6                  2
#7                   2
#8                   2
#9                   3
#10                  3
#11                  5

#Desired output would be:
#   source target weight
#1                   1
#2                   1
#3                   3
#4                   3
#5                   1
#6                  1
#7                   1
#8                   1
#9                   1
#10                  1
#11                  3

我已经彻底查看了 Stack Overflow 社区,但似乎找不到任何有用的东西。老实说,这可能是由于我对该主题的了解有限。这是我的副项目,我正在使用 emo 和遥控器包。

标签: rdataframeunicodeemoji

解决方案


dplyr您可以使用该软件包获取每对表情符号的频率。我认为这是一个比使用循环和计数器更容易的解决方案。与您的方法的唯一区别是表情符号的每个组合只出现一次。希望这有帮助!这是我的解决方案:

library(dplyr)

links %>%
  group_by(source,target) %>% #group by both variables
  count()#Get frequencies for every combination

推荐阅读