1

I need to add to my data a new variable, but I would like to do it using the mutate function. How can I do it? ISLR library

Create a new variable called "HighVol" that has the classes "yes" and "no" to indicate whether the location sold 10,000 units or more in the past year. How many stores produced a high volume?

Example below. 
 carseats.df$HighVol <- factor(carseats.df$HighVol,
                 levels = c(0,1),
                 labels = c("No", "Yes"))
Kat
  • 15,669
  • 3
  • 18
  • 51
Lidieth
  • 11
  • 1

1 Answers1

0

You are going to include the entire data frame if you use mutate. You'll want to whole data frame if the assignment of yes or no is conditionally based on sales.

library(tidyverse)

# create carseats.df
set.seed(39582) # make it repeatable
carseats.df <- data.frame(sales = rnorm(100, 10000, 505))

# now create conditional variable
carseats.df <- carseats.df %>% 
  mutate(HighVol = ifelse(sales > 10000,  # true or false
                          "yes",   # result if true
                          "no") %>% 
           as.factor()) # result if false

head(carseats.df)
#       sales HighVol
# 1  9992.190     yes
# 2 10077.482      no
# 3  9507.145     yes
# 4 10780.788      no
# 5 10433.133      no
# 6 10907.665      no 

It looks like you're fairly new to SO; welcome to the community! If you want great answers quickly, it's best to make your question reproducible. This includes sample data like the output from dput(head(dataObject))) and any libraries you are using. Check it out: making R reproducible questions.

The reason you haven't seen any help is most likely due to the lag of meaningful tags. You only have the tag tree which isn't meaningful. At a minimum, you would want to include a tag for the programming language: r. You could also add things like mutate or the library it's derived from, dplyr.

Kat
  • 15,669
  • 3
  • 18
  • 51
  • Thank you, Kat, I tried o use a different vocabulary, but I keep getting the message that did not let my question go through. I did not know what I was doing wrong. – Lidieth Feb 19 '22 at 06:17
  • Thank you for answering my questions. I am very new to learning the R language and using the community. I will take your advice. – Lidieth Feb 19 '22 at 06:18