根据长数据R的2个条件拉出一个数据

问题描述 投票:0回答:1

我希望我能清楚地表达我的问题。

我是 R 新手,目前正在处理来自 3 个不同语料库的长文本数据。我的目标是了解给定字符串在给定语料库中出现的频率 (%)。这是长数据示例:

Center     n   tag  
 1 apple   19  poetry
 2 melon   34  media
 3 lemon   1   spoken
 4 lemon   1   poetry
 5 peach   1   spoken
 6 apple   1   poetry
 7 orange  1   media
 8 banana  1   spoken
 9 banana  1   media
10 melon   1   media
...

因此,我想根据标签的情况拉出字符串“apple”和“melon”,以及频率。这样,我将能够比较每个不同标签中字符串的频率 (%)。

示例:

Center     %   tag  
 1 apple   4   poetry
 2 apple   34  media
 3 apple   23  spoken
 4 melon   15  poetry
 5 melon   23  spoken
 6 melon   2   poetry

有没有一个功能可以让我做到这一点?我的最终目标是使用 ggplot barplot 可视化数据框。

我仍然想办法在长数据中以这种方式提取数据。我当前的可视化如下:

它只是显示每个标签频率的条形图。我想要的是除了标签之外,它还显示我想要比较的两个字符串变量。测量的不是数字中的频率,而是相对于标签的百分比频率。

r dataframe ggplot2 visualization
1个回答
0
投票

我正在根据“钻石”数据集模拟您的数据。我同意这样的评论,即尚不清楚您想要实现什么,但也许以下内容有所帮助:

library(tidyverse)
## make similar data frame
df <- diamonds %>%
  select(Center = cut, n = table, tag = color)

## define your strings
strings <- c("Premium", "Good")

## filter those
df %>%
  filter(Center %in% strings) %>%
  ## calculate frequency of tag occurrence based on "n" within each Center
  ## this first step might not be necessary depending on how your data looks in real life
  group_by(Center, tag) %>%
  summarise(n = sum(n)) %>%
  ## this calculates the percentatge
  group_by(Center) %>%
  reframe(perc = round(100*n/sum(n)), tag = tag) %>%
  ## then pass this new data frame to ggplot
  ggplot() +
  geom_col(aes(Center, perc, fill = tag))
#> `summarise()` has grouped output by 'Center'. You can override using the
#> `.groups` argument.

创建于 2023-12-29,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.