LonelyToh
LonelyToh

Reputation: 15

ifelse() gave me wrong output

I got a data.frame named DF1

Digit   Country
1       A
1       B
2       C
16      China P Rep
15      Indonesia 

i'm using DF1$Digit <- ifelse(DF1$Digit<=5,"",DF1$Digit) it become

Digit   Country
        A
        B
        C
16      China P Rep
15      Indonesia 

after that i uses DF1$Country2 <- ifelse(DF1$Digit== "","",DF1$Country) For some reason the output is

Digit   Country       Country2
        A         
        B             
        C          
16      China P Rep     36        
15      Indonesia       80

I doesn't know what's the problem here.. Hope someone could help me

Upvotes: 0

Views: 148

Answers (1)

DanY
DanY

Reputation: 6073

Works fine for me as long as Country is a character and not a factor variable:

DF1 <- data.frame(
    Digit = c(1,1,2,16,15),
    Country = c("A", "B", "C", "China", "Indonesia"),
    stringsAsFactors = FALSE
)

DF1$Digit <- ifelse(DF1$Digit<=5,"",DF1$Digit)

DF1$Country2 <- ifelse(DF1$Digit== "","",DF1$Country)

DF1

Output:

  Digit   Country  Country2
1               A          
2               B          
3               C          
4    16     China     China
5    15 Indonesia Indonesia

You can check if Country is a factor variable with str(DF1) or simply is.factor(DF1$Country). If it is a factor variable, you can convert it to character like so:

DF1$Country <- as.character(DF1$County)

Upvotes: 1

Related Questions