删除功能内的数据帧列 [英] Delete data frame column within function
问题描述
我有以下代码:
df<- iris
library(svDialogs)
columnFunction <- function (x) {
column.D <- dlgList(names(x), multiple = T, title = "Spalten auswaehlen")$res
if (!length((column.D))) {
cat("No column selected\n")
} else {
cat("The following columns are choosen:\n")
print(column.D)
for (z in column.D) {
x[[z]] <- NULL #with this part I wanted to delete the above selected columns
}
}
}
columnFunction(df)
那么如何可以动态地解决data.frame列: x [[z]]< - NULL
应该转换为:
So how is it possible to address data.frame columns "dynamically" so: x[[z]] <- NULL
should translate to:
df$Species <- NULL
df[["Species"]] <- NULL
df[,"Species"] <- NULL
,并为每个选定的列选择功能。
有没有人知道如何归档这样的东西?我尝试过几个东西,就像使用粘贴
命令或 sprintf,deparse
,但我没有得到它的工作。我也绑定,通过使用< < -
将data.frame作为全局变量,但也没有帮助。 (这是我第一次甚至听说过)。看起来我错过了将x和z传递给变量赋值的正确方法。
and that for every selected column in every data.frame chosen for the function.
Well does anyone know how to archive something like that? I tried several things like with the paste
command or sprintf, deparse
but i didnt get it working. I also tied to address the data.frame as a global variable by using <<-
but didn`t help, too. (Well its the first time i even heard about that). It looks like i miss the right method transferring x and z to the variable assignment.
推荐答案
如果要创建一个函数 columnFunction
传递的数据框 df
,所有您需要做的是将数据框传递给函数,返回修改版本的 df
,并将结果替换为 df
:
If you want to create a function columnFunction
that removes columns from a passed data frame df
, all you need to do is pass the data frame to the function, return the modified version of df
, and replace df
with the result:
library(svDialogs)
columnFunction <- function (x) {
column.D <- dlgList(names(x), multiple = T, title = "Spalten auswaehlen")$res
if (!length((column.D))) {
cat("No column selected\n")
} else {
cat("The following columns are choosen:\n")
print(column.D)
x <- x[,!names(x) %in% column.D]
}
return(x)
}
df <- columnFunction(df)
这篇关于删除功能内的数据帧列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!