if-else条件基于数据框的列

时间:2018-04-09 15:16:13

标签: r if-statement

我需要根据if-else条件为以下数据框创建一个新列(adminn_final)。如果adminn_needs_update = TRUE,我应该有adminn_final = adminn_updated;否则,adminn_final = adminn_cleaned。当我编写以下代码时,我得到adminn_final列的数字,而不是adminn_updated和adminn_cleaned列中的相应值。任何帮助将不胜感激。

testing2 <- data.frame(adminn_cleaned=c("Sean","Sean"), 
adminn_needs_update=c(TRUE,FALSE), adminn_updated=c("Mike",""))

testing2$adminn_final <- with(testing2, ifelse (adminn_needs_update==TRUE, 
adminn_updated, adminn_cleaned))

1 个答案:

答案 0 :(得分:1)

这是因为adminn_cleanedadminn_updated列是因素。 ifelse语句将因子整数级别分配给新列,而不是与因子级别对应的字符。

要解决此问题,您可以在参数stringsAsFactors = FALSE

中创建传递的数据帧
testing2 <- data.frame(adminn_cleaned=c("Sean","Sean"), 
                   adminn_needs_update=c(TRUE,FALSE),
                   adminn_updated=c("Mike",""),
                   stringsAsFactors = FALSE)

testing2$adminn_final <- with(testing2, ifelse (adminn_needs_update==TRUE, 
                                                adminn_updated,
                                                adminn_cleaned))

testing2

adminn_cleaned adminn_needs_update adminn_updated adminn_final
          Sean                TRUE           Mike         Mike
          Sean               FALSE                        Sean