Home > Back-end >  Create new column with informations from another 2 columns
Create new column with informations from another 2 columns

Time:10-25

I'm new here and I really need help with this thing: I have 2 columns called Recruits and Spawners and I want to create a third one with a combination of this two, like this

Spawners Recruits Class
85.640176 0.000000 Spawners
0.000000 38.30213 Recruits
275.391055 22.031284 Both

The column "Class" is what I need to create, with these condition:

  • If "Spawners" = n and "Recruits" = 0, then "Class" = Spawners
  • If "Spawners" = 0 and "Recruits" = n, then "Class" = Recruits
  • If "Spawners" = n and "Recruits" = n, then "Class" = Both

Thank you very much

CodePudding user response:

You can use case_when to assign class for every condition

library(dplyr)
dat %>% 
  mutate(class = case_when(Spawners > 0 & Recruits == 0 ~ "Spawners",
                           Spawners == 0 & Recruits > 0 ~ "Recruits",
                           Spawners > 0 & Recruits > 0 ~ "Both"))

Output:

  Spawners Recruits    class
1  85.64018  0.00000 Spawners
2   0.00000 38.30213 Recruits
3 275.39105 22.03128     Both

If you wish to have an R base solution, try using a nested ifelse:

dat$class <- with(dat, ifelse(Spawners > 0 & Recruits == 0 , "Spawners",
                 ifelse(Spawners == 0 & Recruits > 0, "Recruits", "Both")))

CodePudding user response:

df <- textConnection('85.640176, 0.000000, "Spawners"
0.000000, 38.30213, "Recruits"
275.391055, 22.031284, "Both"') |> read.csv(header = FALSE) 
colnames(df) <- c('Spawners', 'Recruits', 'Class')
df$class <- apply(df, 1, function(x) {
  cl <- 'Both'
  x1 <- as.numeric(x[ 1 ])
  x2 <- as.numeric(x[ 2 ])
  if ((x1 != 0) & (x2 == 0)) cl <- 'Spawners'
  else if ((x1 == 0) & (x2 != 0)) cl <- 'Recruits'
  cl
})
print(df)

   Spawners Recruits     Class    class
1  85.64018  0.00000  Spawners Spawners
2   0.00000 38.30213  Recruits Recruits
3 275.39105 22.03128      Both     Both

CodePudding user response:

Here is a different approach: My favorit is @Jilber Urbina's answer:

library(dplyr)
library(tidyr)

df %>% 
  mutate(across(1:2, ~case_when(. > 0 ~ cur_column()), .names = 'new_{col}')) %>%
  unite(Class, starts_with('new'), na.rm = TRUE, sep = ' ')

  Spawners Recruits Class            
     <dbl>    <dbl> <chr>            
1     85.6      0   Spawners         
2      0       38.3 Recruits         
3    275.      22.0 Spawners Recruits
  •  Tags:  
  • r
  • Related