ifelse()给我错误的输出

时间:2018-08-24 19:54:04

标签: r if-statement

我有一个名为DF1的data.frame

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

我正在使用DF1$Digit <- ifelse(DF1$Digit<=5,"",DF1$Digit)成为

Digit   Country
        A
        B
        C
16      China P Rep
15      Indonesia 

之后,我使用DF1$Country2 <- ifelse(DF1$Digit== "","",DF1$Country) 由于某种原因,输出是

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

我不知道这里出了什么问题。希望有人能帮助我

1 个答案:

答案 0 :(得分:1)

只要Country是一个字符而不是一个因子变量,对我来说就很好:

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

输出:

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

您可以使用Country或简单地str(DF1)检查is.factor(DF1$Country)是因子变量。如果它是一个因子变量,则可以将其转换为字符,如下所示:

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