r - Converting a specifc column within a function, where the column is specified as function input
问题描述
I am trying to convert a numeric column to a factor column inside a function. The # dataset$variable_name<- as.factor(dataset$variable_name)
works. But obviously I do not want to have the actual variable name in the function.
library(data.table)
DT <- structure(list(variable_name= c(4, 1, 2, 4, 4, 1, 4, 4, 4,
4)), row.names = c(NA, -10L), class = c("data.table", "data.frame"
))
fun <- function(dataset, factorvar) {
# Option 1 works, but is not preferred
# dataset$variable_name<- as.factor(dataset$variable_name)
# Option 2 would be better but does not work
# dataset[,1]<- as.factor(dataset[,1])
# Option 3 would be best but does not work either
dataset[, ..factorvar]<- as.factor(dataset[, ..factorvar])
}
DT <- fun(DT, "variable_name")
解决方案
您可以使用 :
library(data.table)
fun <- function(dataset, factorvar) {
dataset[, (factorvar) := factor(get(factorvar))]
dataset
}
fun(DT, "variable_name")
str(DT)
#Classes ‘data.table’ and 'data.frame': 10 obs. of 1 variable:
# $ variable_name: Factor w/ 3 levels "1","2","4": 3 1 2 3 3 1 3 3 3 3
推荐阅读
- powerbi - 将 r 脚本添加到 power bi
- javascript - jQuery .val() 不返回选项标签的值
- java - 在android中的多个本地通知中设置操作,为广播接收器中的通知提供相同的ID
- python - 如何修复 TypeError:“NoneType”对象在 Python 中不可迭代?
- kubernetes - 将大使部署到 Kubernetes
- json - 使用 Struct 解码 JSON 响应的 Alamofire 错误
- google-cloud-dataproc - Dataproc 集群的数据融合配置失败
- python - 比较行时如何绘制条形图?
- python - 提取字节文本文件中两个字符之间的字符串,Python
- java - Flyway、Spring Boot 和应用程序在没有数据库的情况下启动