我有一个数据帧contr_factors,有1932行和以下列: state、unarmed、not_flee、white_victim、attacked。我想要更改数据集中的因子,并编写了以下代码:
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`)但是我有一个错误: Error in levels(df$df_col) <- c("name1","name2"):尝试将属性设置为NULL。
发布于 2017-01-22 07:11:27
如果你能提供一些示例代码,那就太好了。这可以使这件事变得更容易,但您有两个选择。
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包来简化这一过程,或者使用不同的方法访问数据框中的列。
https://stackoverflow.com/questions/41784140
复制相似问题