修改R因子?

时间:2015-10-22 17:15:50

标签: r

假设在R中有一个Data.Frame对象,其中所有字符列都已转换为因子。我需要然后修改"与数据帧中某一行相关联的值 - 但将其编码为一个因子。我首先需要提取一行,所以这就是我正在做的事情。这是一个可重复的例子

Berkshelf

当我指定" ca"到newdat [" col1"]与数据中该列相关联的Factor对象被字符串" ca"覆盖。这不是预期的行为。相反,我想修改编码newdat中存在哪个级别的数值。所以我想更改newdat [" col1"]的内容如下:

在:

$(/opt/chefdk/bin/chef shell-init $(basename $SHELL))
sudo /opt/chefdk/embedded/bin/gem install $kitchen_plugin_gem_name_here

后:

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"

我该如何做到这一点?

1 个答案:

答案 0 :(得分:3)

你在做什么相当于:

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

即。将新对象分配给现有符号。在您的示例中,您只需替换&#34;因子&#34; newdat["col1"]与&#34; ca&#34;。 相反,要分配给一个因子(在NA中对非级别结果进行子分配),您可以使用

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

在您的示例中(我使用local避免一次又一次地更改newdat):

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