【问题标题】:Convert the text data in one column into numeric data in R将一列中的文本数据转换为R中的数字数据
【发布时间】:2020-04-30 09:47:48
【问题描述】:

我的数据框中有一列作为电影类型,其中有很多。 我想将其转换为用于绘制相关矩阵的数值数据。请帮我做。

Genre         Genre_numerical
Comedy        1
Action        2
Suspense      3
Comedy        1
Biography     4

【问题讨论】:

    标签: r dataframe data-wrangling


    【解决方案1】:

    在 R 中,您可以制作分类数据的因子。这是 R 中要做的基本事情(或避免直到最后一刻)。如果您需要重新整理,请查看无序和无序因素。

    您的问题似乎更多地涉及如何关联分类数据的问题。

    看看这个答案,然后阅读线程:Plot the equivalent of correlation matrix for factors (categorical data)? And mixed types?

    使用偏差校正的 Cramer's V 计算名义与名义的关联强度、使用 Spearman(默认)或 Pearson 相关计算数值与数值以及使用 ANOVA 计算名义与数值的关联强度。 - @Holger Brandl

    【讨论】:

      【解决方案2】:

      这里有两种解决方案,一种是base R,另一种是基于dplyr

      说明性数据:

      set.seed(123)
      df <- data.frame(Genre = sample(c("Comedy", "Action", "Suspense", "Biography"), 10, replace = T))
      

      解决方案 #1

      您可以使用ifelse 为您的Genre 类别分配数值:

      df$Genre_numerical <- ifelse(df$Genre == "Comedy", 1,
                                  ifelse(df$Genre == "Action", 2,
                                         ifelse(df$Genre == "Suspense", 3, 4)))
      

      解决方案 #2

      library(dplyr)
      df$Genre_numerical <- df %>% 
        mutate(Genre = case_when(Genre == "Comedy"   ~ 1,
                                 Genre == "Action"   ~ 2,
                                 Genre == "Suspense" ~ 3, 
                                 TRUE                ~ 4))
      

      结果:

      两种情况的结果都是一样的:

      df
             Genre Genre_numerical
      1     Action               2
      2  Biography               4
      3     Action               2
      4  Biography               4
      5  Biography               4
      6     Comedy               1
      7   Suspense               3
      8  Biography               4
      9   Suspense               3
      10    Action               2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-23
        • 1970-01-01
        • 2019-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多