I have a dataframe and select one row to obtain one row but maintain the levels. I need this row to use predict() with a model later one.
I try to change one value of the row by assigning a characters (?) to a factor level like this:
df <- data.frame(some_amazing_column = c("yes", "no"))
levels(df$some_amazing_column)
row <- head(df, 1)
char <- "no"
head(row)
levels(row$some_amazing_column)
row$some_amazing_column = char
levels(row$some_amazing_column)
This loses the factor levels. Am I changing the value (factor level) correctly? What is the right way to change, in this case, yes to no whilst maintaining the levels. please not that the assigned value is a character coming from a front-end.
PS:
The accepted answer's hint results in this working code:
df <- data.frame(some_amazing_column = c("yes", "no"))
levels(df$some_amazing_column)
row <- head(df, 1)
char <- "no"
head(row)
levels(row$some_amazing_column)
row$some_amazing_column <- factor(char, levels = levels(row$some_amazing_column))
head(row)
levels(row$some_amazing_column)
To change the level, one way is to convert the 'char' to factor
with same levels
as in the original dataset and assign
row$some_amazing_column <- factor(char, levels = levels(row$some_amazing_column))
levels(row$some_amazing_column)
#[1] "no" "yes"
row
# some_amazing_column
#1 no
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.