【问题标题】:Dynamic adding of columns in RR中动态添加列
【发布时间】:2017-06-20 13:07:30
【问题描述】:

我需要一些帮助来找到一种动态添加列的好方法,这些列具有我需要从字符串中提取的不同类别的计数。

在我的数据中,我有一列包含类别名称及其计数。这些字段可以为空,也可以包含任何可以想到的类别组合。以下是一些示例:

themes:firstcategory_1;secondcategory_33;thirdcategory_5
themes:secondcategory_33;fourthcategory_2
themes:fifthcategory_1

我需要的是每个类别的列(应该有类别的名称)和从上面的字符串中提取的计数。类别列表是动态的,所以我事先不知道存在哪些类别。

我该如何处理?

【问题讨论】:

  • 请在表格中包含您想要的输出,以便我们更好地了解您要查找的内容。还包括您尝试解决此问题的任何代码以及出现问题的地方。

标签: r


【解决方案1】:

此代码将为每个类别获取一列,其中包含每行的计数。

library(dplyr)
library(tidyr)
library(stringr)

# Create test dataframe
df <- data.frame(themes = c("firstcategory_1;secondcategory_33;thirdcategory_5", "secondcategory_33;fourthcategory_2","fifthcategory_1"), stringsAsFactors = FALSE)

# Get the number of columns to split values into
cols <- max(str_count(df$themes,";")) + 1

# Get vector of temporary column names
cols <- paste0("col",c(1:cols))

df <- df %>%
      # Add an ID column based on row number
      mutate(ID = row_number()) %>%
      # Separate multiple categories by semicolon
      separate(col = themes, into = cols, sep = ";", fill = "right") %>%
      # Gather categories into a single column
      gather_("Column", "Value", cols) %>%
      # Drop temporary column
      select(-Column) %>%
      # Filter out NA values
      filter(!is.na(Value)) %>%
      # Separate categories from their counts by underscore
      separate(col = Value, into = c("Category","Count"), sep = "_", fill = "right") %>%
      # Spread categories to create a column for each category, with the count for each ID in that category
      spread(Category, Count)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    相关资源
    最近更新 更多