使用if not condition替换列中的值

时间:2017-06-06 11:24:04

标签: r dataframe conditional-statements

我有以下数据farme,

head(df)
    Sample type
    AA01   ph
    AA02   RH
    AA03   CH
    AA04   TCH

如果值不等于column typeph,我需要替换others中的值。 所以我尝试了如下,

df$type[which(df$type != "ph")] = "others"

但它的投掷警告为,

Warning message:
In `[<-.factor`(`*tmp*`, which(df$type != "ph"), value = c(NA,  :
  invalid factor level, NA generated

任何解决方案或建议都会很棒

1 个答案:

答案 0 :(得分:1)

试试这个:

Sample = c("AA01", "AA02", "AA03", "AA04")
type = c("ph", "RH", "CH", "TCH")

df = as.data.frame(cbind(Sample, type))
df$type = as.character(df$type)
df$type = ifelse(df$type == "ph", "others", df$type)
df