简体   繁体   中英

Categorizing numerate data in a column based on if it's lower or greater than 0, and putting the results in a new column in R

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.

Here a tidyverse approach

B <- -567:700

df <- data.frame(B = B)

library(dplyr)

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

Using base R

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

If we want to split

split(df, df$B > 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM