【问题标题】:Combine different observations into new variable [duplicate]将不同的观察结果组合成新变量[重复]
【发布时间】:2021-09-23 17:56:31
【问题描述】:

我一直在尝试使用 barplot 或 ggplot 制作图表,但首先我需要结合来自同一个变量的不同观察结果。

我的变量有不同的观察结果,具体取决于主题与每个用户的相关程度。像这样:

Count  Activity
10     Bikes for fitness reasons
22     Runs for fitness reasons
12     Bikes to commute to work
10     Walks to commute to work
5      Walks to stay healthy

我的想法是合并来自“Activity”变量的观察结果,如下所示:

Count Activity
22    Bikes
22    Runs
15    Walks

所以,我不在乎他们进行活动的原因,我只想将它们合并,以便将这些信息放入条形图中。

【问题讨论】:

  • 到目前为止你有什么尝试?

标签: r


【解决方案1】:

这是tidyverse 解决方案:

library(tidyverse)

df %>% 
  mutate(Activity = word(Activity, 1)) %>% 
  group_by(Activity) %>% 
  summarize(Count = sum(Count))

这给了我们:

# A tibble: 3 x 2
  Activity Count
  <chr>    <dbl>
1 Bikes       22
2 Runs        22
3 Walks       15

数据:

structure(list(Count = c(10, 22, 12, 10, 5), Activity = c("Bikes for fitness reasons", 
"Runs for fitness reasons", "Bikes to commute to work", "Walks to commute to work", 
"Walks to stay healthy")), row.names = c(NA, -5L), class = c("data.table", 
"data.frame"), .internal.selfref = <pointer: 0x0000019ba0e31ef0>)

【讨论】:

  • 不知道word()。看起来很有用。我通常会在这里通过str_extract("^\\w+") 钻头和类似的东西。这要简单得多。 +1
【解决方案2】:

您可以使用grep() 来查找您要查找的每个术语,如下所示:

df <- data.frame(
  Count = c(10,22,12,10,5),
  Activity = c("Bikes for fitness reasons",
               "Runs for fitness reasons",
               "Bikes to commute to work",
               "Walks to commute to work",
               "Walks to stay healthy"))

# Look for this string
var <- "Bikes"

# Get the row where "Bikes" appears
grep(pattern = var, x = df$Activity)
#> [1] 1 3

# Get Count values from each row where "Bikes" appears
df[grep(pattern = var, x = df$Activity), "Count"]
#> [1] 10 12

【讨论】:

    【解决方案3】:

    使用trimws

    library(dplyr)
    df %>% 
       group_by(Activity = trimws(Activity, whitespace = "\\s+.*")) %>% 
       summarise(Count = sum(Count))
    

    -输出

    # A tibble: 3 x 2
      Activity Count
      <chr>    <dbl>
    1 Bikes       22
    2 Runs        22
    3 Walks       15
    

    【讨论】:

      猜你喜欢
      • 2019-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-19
      • 1970-01-01
      相关资源
      最近更新 更多