【问题标题】:Adding a column to a data frame using mutate in R在 R 中使用 mutate 将列添加到数据框中
【发布时间】:2019-09-18 13:59:55
【问题描述】:

我正在使用 ISLR 包中的 OJdata 集。我需要将列添加到数据框中。一列是两个数值变量的乘积。第二列是数值变量和分类变量的乘积。

我在 R 的 dplyr 包中使用 mutate 函数添加了第一列(数字*数字),如下所示,

require(ISLR)
OJ %>% 
  mutate(`StoreID:PriceCH` = StoreID*PriceCH)

我能够成功地添加这个库。但是当我在添加分类*数字列时尝试做同样的事情时,我得到了一个错误。

OJ %>% 
  mutate(`Store7:PriceCH` = Store7*PriceCH)

Warning message:
In Ops.factor(Store7, PriceCH) : ‘*’ not meaningful for factors 

如果我需要添加 categorical*numerical 乘积的 coulmn,谁能建议我能做什么?

我的输出应该是这样的,

谢谢

【问题讨论】:

  • 我没有使用图片来展示数据。我使用图像来显示我的预期输出。
  • 您打算如何将分类变量转换为数字,或者以其他方式乘以某个类别?

标签: r data-manipulation dplyr


【解决方案1】:

首先对Store7 应用单热编码:

OJ <- cbind(OJ, sapply("Yes", function(x) as.integer(x == OJ$Store7)))
names(OJ)[ncol(OJ)] <- "Store7_Yes"

【讨论】:

    【解决方案2】:

    从概念上讲,我没有多大意义(在大多数情况下)乘以分类变量。

    如果您想这样做,您必须将数据转换为数字刻度。请注意,这并不总是那么简单。

    这可能是一个起点:

    library(tidyverse)
    
    Result <- OJ %>% 
      mutate(`StoreID:PriceCH` = StoreID*PriceCH) %>% 
      mutate(Store7Numeric = as.character(Store7)) #To avoid possible mistakes
    
    Result <- Result %>% 
      mutate(Store7Numeric = ifelse(Store7Numeric == "No", 0, 1)) #Check this
    
    Result <- Result %>% mutate(Store7Numeric = as.numeric(Store7Numeric)) %>% #To numeric
    mutate(`Store7:PriceCH` = Store7Numeric*PriceCH) %>% #Your calculation
    select(-Store7Numeric) #Remove, if you want. the created numeric variable
    

    【讨论】:

      【解决方案3】:

      错误消息是由于变量Store7factor(参见str(OJ)),所以你必须使它成为numeric

      OJ$Store7 <- as.numeric(OJ$Store7)
      

      【讨论】:

        猜你喜欢
        • 2022-08-23
        • 2023-01-29
        • 1970-01-01
        • 2015-04-23
        • 1970-01-01
        • 1970-01-01
        • 2014-12-28
        • 1970-01-01
        • 2020-08-02
        相关资源
        最近更新 更多