我试图在一个函数中使用fct_recode &它给出了一个错误:" error:f必须是一个因子(或字符向量)“。
编辑:如果我运行它,它会直接工作,不确定如何将它合并到函数中
df[,"c1"] <- as.character(df$c1)
df[,"c1"] <- fct_recode(df$c1,
"Female" = "2",
"Male" = "1")当我将df,c1更改为df$c1时,它起作用了,我不确定为什么,也不确定如何将其构建到我的recode函数中
我正在尝试的代码
recode <- function(data, var1)
{
data[,var1]
data[,var1] <- as.character(data[,var1])
data[,var1] <- fct_recode(data[,var1],
"Yes" = "1",
"No" = "2")
data[,var1] <- fct_explicit_na(data[,var1],"No")
return(data)
}
recode(df,"c1")使用下面的commant发现df数据集的c1列的结构(它是一个很大的数据集,因此共享一列的dput,如果有问题请告诉我)
df[,"c1"] %>% head(10) %>% dput()
structure(list(c1 = c(2, 1, 2, 1, 1, 2, 2, 1, 1, 2)), notes = c("b15 urinary creatinine is in mg/dl",
"3", "the province variable is related to province", "the stratum variable is about urban and rural classification"
), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"
))
str(df$c1) #gives below output
num [1:5610] 2 1 2 1 1 2 2 1 1 2 ...
- attr(*, "label")= chr "C1"
- attr(*, "format.stata")= chr "%10.0g"函数必须失败的任何原因
发布于 2019-07-14 00:11:07
当我使用[[ notation,我不确定为什么当我使用df,var1 notation时它会失败,但是工作代码如下所示
recode <- function(data, var1)
{
data[[var1]] <- as.character(data[[var1]])
data[[var1]] <- fct_recode(data[[var1]],
"Female" = "2",
"Male" = "1"
)
data[[var1]] <- fct_explicit_na(data[[var1]],"No")
return(data[[var1]])
}
recode(df,"c1")https://stackoverflow.com/questions/57012791
复制相似问题