Replace contents of factor column in R dataframe

后端 未结 8 1631
我在风中等你
我在风中等你 2020-11-28 20:59

I need to replace the levels of a factor column in a dataframe. Using the iris dataset as an example, how would I replace any cells which contain virginic

相关标签:
8条回答
  • 2020-11-28 21:39

    You want to replace the values in a dataset column, but you're getting an error like this:

    invalid factor level, NA generated

    Try this instead:

    levels(dataframe$column)[levels(dataframe$column)=='old_value'] <- 'new_value'

    0 讨论(0)
  • 2020-11-28 21:40

    A more general solution that works with all the data frame at once and where you don't have to add new factors levels is:

    data.mtx <- as.matrix(data.df)
    data.mtx[which(data.mtx == "old.value.to.replace")] <- "new.value"
    data.df <- as.data.frame(data.mtx)
    

    A nice feature of this code is that you can assign as many values as you have in your original data frame at once, not only one "new.value", and the new values can be random values. Thus you can create a complete new random data frame with the same size as the original.

    0 讨论(0)
提交回复
热议问题