0
if (crabs$FL >= median(crabs$FL)) {crabs$FLG <- "L"} else {crabs$FLG <- "S"}

crabs is the data name and FL is a variable name. I am trying to create a variable name "FLG" if FL is greater than median.

But it says the condition has length > 1 and only the first element will be used. It created FLG but it seems like only the first row's value is used to create it.

if (crabs$FL[i] >= median(crabs$FL)) {crabs$FLG <- "L"} else {crabs$FLG <- "S"}

I tried this one. But now it says Error in if (crabs$FL[i] >= median(crabs$FL)) { : missing value where TRUE/FALSE needed.

Give me any idea to fix this error please!!

camille
  • 16,432
  • 18
  • 38
  • 60
somi gim
  • 17
  • 4
  • The first message you posted is a warning, not an error—the code still runs. Beyond that, it's hard to say without a [reproducible example](https://stackoverflow.com/q/5963269/5325862). What is `i`? – camille Jun 11 '21 at 00:30
  • Have you tried this? https://stackoverflow.com/questions/14170778/interpreting-condition-has-length-1-warning-from-if-function – Ronak Shah Jun 11 '21 at 02:09

2 Answers2

0

If you don't mind the tidyverse way, this code should get you to what you want.

library(tidyverse)
crabs <- data.frame(FL = c(1,2,3,4,5,50000))

crabs_2 <- crabs %>%
  mutate(
   FLG = case_when(
     FL >= median(FL) ~ 'L',
     TRUE ~ 'S'
   ) 
  )
Papuha
  • 103
  • 6
0

Maybe:

mutate(crabs, FLG = if_else(FL >= median(crabs$FL), 'L', 'S'))
jpdugo17
  • 6,816
  • 2
  • 11
  • 23