R更改数据集中的因子

时间:2017-01-21 20:31:00

标签: r function factors

我有一个数据框contr_factors,有1932行和以下列: 国家,徒手,not_flee,white_victim,受到攻击。我想更改数据集中的因素,我写了这段代码:

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")`

但我想制作我的代码分拣机,并尝试了这个功能:

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`)

但我有一个错误: 级别错误(df $ df_col)&lt; -c(&#34; name1&#34;,&#34; name2&#34;):   尝试在NULL上设置属性。

1 个答案:

答案 0 :(得分:0)

如果要提供一些示例代码,那就太好了。这可以使这更容易,但你有两个选择。

 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`)

另一种选择是接受Rich的建议。问题是$后来遇到麻烦了。您可以考虑使用lazyeval包来简化这一过程,或者使用不同的方法来访问数据框中的列。