gpt4 book ai didi

r - 修改 R 因子?

转载 作者:行者123 更新时间:2023-12-04 11:30:19 27 4
gpt4 key购买 nike

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

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"

当我将“ca”分配给 newdat[“col1”] 时,与数据中该列关联的 Factor 对象被字符串“ca”覆盖。这不是预期的行为。相反,我想修改对 newdat 中存在的级别进行编码的数值。所以我想改变 newdat["col1"] 的内容如下:

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

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

我怎样才能做到这一点?

最佳答案

你在做什么相当于:

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

即将一个新对象分配给现有符号。在您的示例中,您只需替换 newdat["col1"] 的“因子”即可。与“ca”。
相反,要子分配给一个因子(子分配一个非级别导致 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

关于r - 修改 R 因子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33286807/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com