0

I have a dataset where I want to create a new column and add values based on the value present in each row. below is the example

Sales Result of new column 100 Low 200 Low 300 Moderate 400 High 500 High

Below is the code i tried to get result

data$New_Column = for (Sal in data$Sales){
  if(Sal > 300){
  print("High")
} else if(Sal == 300){
  print("Moderate")
}else{
  print("Low")
}
  
}

Thank You

1
  • It is considered polite to accept an answer that has answered your OP. This helps others who are looking for a solution for the same/similar query. Furthermore, people may be willing to help you in your future queries. Commented Feb 28, 2021 at 16:07

2 Answers 2

2

You would usually not do that in a loop in R since most of the relevant functions can work directly with vectors.

Here is one option using data.table::fcase() and another using ifelse() from base R:

library(data.table)

data$New_Column  <- fcase(
  data$Sales > 300, "High",
  data$Sales == 300, "Moderate",
  data$Sales < 300, "Low"
)

# Using base R only:
data$New_Column  <-
  ifelse(data$Sales == 300, "Moderate", ifelse(data$Sales > 300, "High", "Low"))

#   Sales New_Column
# 1   300   Moderate
# 2   500       High
# 3   200        Low
# 4   500       High
# 5   400       High
# 6   500       High
# 7   400       High
# 8   300   Moderate

Example input data

set.seed(13L)
data <- data.frame(
  Sales = sample(seq(100, 500, 100), size = 8L, replace = TRUE)
)
Sign up to request clarification or add additional context in comments.

Comments

1

Perhaps try using mutate instead of a loop:

newdat <- data %>>% mutate(New_Column, if(Sal==300 = "moderate"), ifelse(Sal>300, "High", "Low")

3 Comments

Note that if is not vectorised, whereas ifelse is. Thus you would call ifelse(Sal == 300, "moderate", ifelse(Sal > 300, "High", "Low")). Also Sal==300 = "moderate" throws an error!
Dear Jamie, Thanks for reverting, i tried, but the above solution is not generating the desired output.
Good catch David! It looks like he got it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.