Replace value with Factor in r data.table

2019-07-20 14:16发布

问题:

I have a data set that has a column for a factor (in the example case, cut). It is currently set up like this:

library(ggplot2) # access to diamonds dataset
library(data.table)
data <- data.table(diamonds)[,list(mean_carat=mean(carat)), by=c('cut', 'color')]

I am trying to change all entries named "Fair" to "Good" because in my data set, the two entries are actually the same thing but notated differently. The syntax that I have been trying to use is:

data[which(cut = "Fair"), cut := "Good"]

and the output is

>Error: unexpected symbol in "data[which(cut = "Fair"), cut := "Good"]"

Can anyone tell me where I am going wrong?

回答1:

You used = instead of ==. Try

data[which(cut == "Fair"), cut := "Good"]

You also don't actually need the which statement:

data[cut == "Fair", cut := "Good"]