Home > OS >  Categorizing numerate data in a column based on if it's lower or greater than 0, and putting th
Categorizing numerate data in a column based on if it's lower or greater than 0, and putting th

Time:01-12

Sorry for the long winded title, not sure how to explain it. I have a dataset in R with lots of observations and 15 variables. One of these Variables, 'B' is continous numerate data ranging from -567 to 700.

Basically, if the number in column 'B' is less than 0, I want to label it as '1' and create a new column 'X' to store the '1' categorical variable in there. Likewise, if the number is greater than 0 I want it to be labelled '2' and also stored in the new column 'X'.

New to R so struggling, not sure of a quick and easy way to do it.

CodePudding user response:

Here a tidyverse approach

B <- -567:700

df <- data.frame(B = B)

library(dplyr)

df %>% 
  mutate(X = if_else(B < 0, 1, 2))

CodePudding user response:

Using base R

df$X <- 1   (df$B > 0)

If we want to split

split(df, df$B > 0)
  • Related