Modifying an R factor?

Say have a Data.Frame object in R where all the character columns have been transformed to factors. I need to then "modify" the value associated with a certain row in the dataframe -- but keep it encoded as a factor. I first need to extract a single row, so here is what I'm doing. Here is a reproducible example

a = c("ab", "ba", "ca")
b = c("ab", "dd", "da")
c = c("cd", "fa", "op")
data = data.frame(a,b,c, row.names = c("row1", "row2", "row3")
colnames(data) <- c("col1", "col2", "col3")
data[,"col1"] <- as.factor(data[,"col1"])
newdat <- data["row1",]
newdat["col1"] <- "ca"

When I assign "ca" to newdat["col1"] the Factor object associated with that column in data was overwritten by the string "ca". This is not the intended behavior. Instead, I want to modify the numeric value that encodes which level is present in newdat. so I want to change the contents of newdat["col1"] as follows:

Before:

Factor object, levels = c("ab", "ba", "ca"): 1 (the value it had)

After:

Factor object, levels = c("ab", "ba", "ca"): 3 (the value associated with the level "ca")

How can I accomplish this?


What you are doing is equivalent to:

x = factor(letters[1:4]) #factor
x1 = x[1] #factor; subset of 'x'
x1 = "c" #assign new value

ie assign a new object to an existing symbol. In your example, you, just, replace the "factor" of newdat["col1"] with "ca". Instead, to subassign to a factor (subassigning wit a non-level results in NA ), you could use

x = factor(letters[1:4])
x1 = x[1]
x1[1] = "c"  #factor; subset of 'x' with the 3rd level

And in your example (I use local to avoid changing newdat again and again for the below):

str(newdat)
#'data.frame':   1 obs. of  3 variables:
# $ col1: Factor w/ 3 levels "ab","ba","ca": 1
# $ col2: Factor w/ 3 levels "ab","da","dd": 1
# $ col3: Factor w/ 3 levels "cd","fa","op": 1
local({ newdat["col1"] = "ca"; str(newdat) })
#'data.frame':   1 obs. of  3 variables:
# $ col1: chr "ca"
# $ col2: Factor w/ 3 levels "ab","da","dd": 1
# $ col3: Factor w/ 3 levels "cd","fa","op": 1    
local({ newdat[1, "col1"] = "ca"; str(newdat) })
#'data.frame':   1 obs. of  3 variables:
# $ col1: Factor w/ 3 levels "ab","ba","ca": 3
# $ col2: Factor w/ 3 levels "ab","da","dd": 1
# $ col3: Factor w/ 3 levels "cd","fa","op": 1
local({ newdat[["col1"]][1] = "ca"; str(newdat) })
#'data.frame':   1 obs. of  3 variables:
# $ col1: Factor w/ 3 levels "ab","ba","ca": 3
# $ col2: Factor w/ 3 levels "ab","da","dd": 1
# $ col3: Factor w/ 3 levels "cd","fa","op": 1
链接地址: http://www.djcxy.com/p/29934.html

上一篇: 在Pod结构中出错状态

下一篇: 修改R因子?