2

I'm working with a column in a dataframe of numeric data called "L_D" which has a range of values from 0.6-1.9. I'm trying to create a new column that categorizes the range in 3 ranges: "high" for L_D>1.4, "low" for L_D<0.9, or "medium".

#add L/D grouping to CompStrngth, <0.9=Low aspect ratio; >1.4=High Aspect Ratio, else = other raio
ifelse(CompStrngthData$L_D > 1.4, CompStrngthData$L_D_group <- "high",
   ifelse(CompStrngthData$L_D > 0.9, CompStrngthData$L_D_group <- "medium",
        CompStrngthData$L_D_group <- "low" )
)

When I run this code, it produces the desired result in the console. But when I open up the dataframe, it produces a column filled with "low".

Because of that I found the cut function and it works great with the desired results

CompStrngthData$L_D_group <- cut(CompStrngthData$L_D, breaks = c(-Inf,0.9,1.4,Inf), labels = c("low", "medium", "high"))

I'm sure it's a simple mistake I'm overlooking with the dataframe or if else function, just looking to understand my error.

2
  • 1
    I've never seen a situation where assignment within the yes= or no= arguments of ifelse was a reasonable thing to do. While it is syntactically legal to do so, it's always (imo) been more confusing than not, so like @akrun's answer, I always keep assignments outside of ifelse (nested or otherwise). Commented Mar 29, 2020 at 17:43
  • Can you dput your data to help reproduce and troubleshoot the issue you are running into? Commented Mar 29, 2020 at 17:44

1 Answer 1

2

The issue could be with the assignment inside the ifelse, instead, take it outside

CompStrngthData$L_D_group <- ifelse(CompStrngthData$L_D > 1.4,  "high",
    ifelse(CompStrngthData$L_D > 0.9, "medium",
    "low" )
         )
Sign up to request clarification or add additional context in comments.

1 Comment

That is it! Knew it was something simple like that. Though, I much prefer the cut function, especially if I was working with more groupings.

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.