R 从变量名列表创建变量表

标签 r data.table

我目前正在尝试从变量名称列表创建一个表(我觉得应该相对简单),但我一生都无法弄清楚如何正确执行它。

我有一个名为"file"的数据表,该文件中有一个包含 3 个变量名称的列表。我想要做的是创建每个变量的表,然后将它们绑定(bind)在一起。为了进一步了解上下文,这几行代码将被加工成一个更大的函数。变量名称列表必须能够容纳用户定义的变量数量。

我尝试过以下方法:

file<-as.data.table(dt)
variable_list<-list("outcome", "type")

for (variable in variable_list){
var_table<-as.data.table(table(file$variable_list))
na_table<-as.data.table(table(is.na(file$variable)))
}

当我运行上面的代码时,R 返回 var_table 和 na_table 的空表。我做错了什么?

最佳答案

一个选项是循环遍历'variable_list,提取列,应用tablerbindwithindo.call`

do.call(rbind, lapply(variable_list, function(nm) table(file[[nm]])))

注意:假设列的级别相同

如果级别不同,请通过将列转换为指定级别因子来使其相同

lvls <- na.omit(sort(unique(unlist(file[, unlist(variable_list), with = FALSE]))))

do.call(rbind, lapply(variable_list, function(nm)
       table(factor(file[[nm]], levels = lvls))))

或者,如果我们有 data.table,请使用 data.table 方法

rbindlist(lapply(variable_list, function(nm) file[, .N,by = c(nm)]), fill = TRUE)

关于R 从变量名列表创建变量表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66125157/

相关文章:

java - 在这种情况下如何设置R.string.resource_name

R:将日期向下舍入到一周的第一天

r - googleUser.getAuthResponse().id_token 不返回 Shiny 的 id_token

r - R : Replace a column value with a value from same column after matching two other columns values 中的数据表

r - 如何检查 data.table 各行中的值是否相同

r - 动物园里的动物 : can we aggregate a daily time series of factors and flag activity by ID?

javascript - RSelenium:向下滚动以加载网页内容

r - 包/命名空间环境中同名函数的值/引用相等?

R data.table 替换多列中的值

R data.table 使用任何划分列集和标志