数据集中的R变化因子

数据集中的R变化因子,r,function,factors,R,Function,Factors,我有一个数据框contr_factors,包含1932行和以下列: 国家,手无寸铁,不是逃跑,白人受害者,被袭击。我想更改数据集中的因子,我编写了以下代码: contr_factors$unarmed <- as.factor(contr_factors$unarmed) levels(contr_factors$unarmed) <- c("Armed", "Unarmed") contr_factors$white_victim <- as.factor(contr_fac

我有一个数据框contr_factors,包含1932行和以下列: 国家,手无寸铁,不是逃跑,白人受害者,被袭击。我想更改数据集中的因子,我编写了以下代码:

contr_factors$unarmed <- as.factor(contr_factors$unarmed)
levels(contr_factors$unarmed) <- c("Armed", "Unarmed")
contr_factors$white_victim <- as.factor(contr_factors$white_victim)
levels(contr_factors$white_victim) <- c("Non-white", "White")
contr_factors$not_flee <- as.factor(contr_factors$not_flee)
levels(contr_factors$not_flee) <- c("Flee", "Not flee")
contr_factors$attacked <- as.factor(contr_factors$attacked)
levels(contr_factors$attacked) <- c("Not attack", "attack")`

contr\u factors$unarmed如果您能提供一些示例代码,那就太好了。这可能会使这更容易,但你有两个选择

 change_factors <- function(df, df_col, `name1`, `name2`) {
       as.factor(df[,df_col]) 
       levels(df[,df_col] <- c("name1", "name2")
       }

 change_factors(contr_factors, "not_flee", `Flee`, `Not flee`)

change\u factors您应该使用
df[[df\u col]]
not
df$df\u col
然后使用
“not\u flue”
(带引号)调用函数。已经有一个内置函数可以满足您的需要<代码>因子(contr_factors$unarmed,levels=c(“Armed”,“unarmed”)
。它还有一个
labels
参数,允许您根据需要重新标记级别。
 change_factors <- function(df, df_col, `name1`, `name2`) {
       as.factor(df[,df_col]) 
       levels(df[,df_col] <- c("name1", "name2")
       }

 change_factors(contr_factors, "not_flee", `Flee`, `Not flee`)