Create column with another column value if conditon is TRUE

Asked

Viewed 49 times

2

I am trying to create a column x, with the value of column A, if the value of column B == X, if not = 0

Example:

sales<-c(100,140,200,300,20,1000,200,3000)

vendedor<-c("A","B","A","B","C","C","D","A")

regiao<-c("North","South","East","North","South","North","East","South"")

df<-data.frame(seller, region, sales)

newcol would be :
if region == 'north' take the seller’s value, Else 0

outworking

newcol = "A",0,0,"B",0,"C",0,0

1 answer

2


The ifelse of R itself exists for exactly this situation, applying an if/Else to a vector in a more compact way.

#ifelse aplica um if/else a um vetor

ifelse(c(1, 0, 3) > 0, "SIM", "NÃO")
#> [1] "SIM" "NÃO" "SIM"

#aplicado nos seus dados
vendas<-c(100,140,200,300,20,1000,200,3000)

vendedor<-c("A","B","A","B","C","C","D","A")

regiao<-c("Norte","Sul","Leste","Norte","Sul","Norte","Leste","Sul")

df<-data.frame(vendedor,regiao,vendas)

df['newcol'] = ifelse(df$regiao == "Norte", df$vendedor, 0)

df
#>   vendedor regiao vendas newcol
#> 1        A  Norte    100      A
#> 2        B    Sul    140      0
#> 3        A  Leste    200      0
#> 4        B  Norte    300      B
#> 5        C    Sul     20      0
#> 6        C  Norte   1000      C
#> 7        D  Leste    200      0
#> 8        A    Sul   3000      0

#ou com o tidyverse
library(tidyverse)

df<-data.frame(vendedor,regiao,vendas)

df %>% 
  mutate(newcol = ifelse(regiao == "Norte", vendedor, 0))
#>   vendedor regiao vendas newcol
#> 1        A  Norte    100      A
#> 2        B    Sul    140      0
#> 3        A  Leste    200      0
#> 4        B  Norte    300      B
#> 5        C    Sul     20      0
#> 6        C  Norte   1000      C
#> 7        D  Leste    200      0
#> 8        A    Sul   3000      0

Created on 2020-10-03 by the reprex package (v0.3.0)

  • For some reason I have the return of numbers, not the associated value A B C or D df$newcol [1] 1 0 0 2 0 3 0 0

  • Column with ABCD is a factor? If yes use ifelse so ifelse(df$regiao == "Norte", as.character(df$vendedor), 0) works. Or as.character(vendedor) in the example with tidyverse

  • 1

    I just came in here again to comment on this, the column was as factor, I transformed it with the.Haracter and it worked :) Thanks for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.