在我的数据框中有许多指定的列,我想删除它们。我将目标列名存储在一个列表中,我想要消除使用它,也许这就是问题所在。 即使这不起作用:
for(i in 1:(length(columnnames))){
temp <- columnnames[i]
DF$temp <- NULL
}
因为这个:
print(ncol(DF))
我得到了原始列数。
答案 0 :(得分:1)
一种方法
DF <- data.frame(A = c("a","a","a"), B = c("b","b","b"), C = c("c","c","c")) # Your data set
columnnames <- c("A", "B") # The columns you want to erase
DF <- DF[setdiff(names(DF), columnnames)]
答案 1 :(得分:0)
尝试这样的事情:
for (i in columnnames) DF[[i]] <- NULL
或者一气呵成:
DF[columnnames] <- vector('list', length(columnnames))
答案 2 :(得分:0)
使用大卫的示例数据,您也可以使用list(NULL)
而不仅仅是NULL
:
## Your data.frame
DF <- data.frame(A = c("a","a","a"),
B = c("b","b","b"),
C = c("c","c","c"))
## The columns you want to remove
columnnames <- c("A", "B")
## Removing them...
DF[columnnames] <- list(NULL)
DF
# C
# 1 c
# 2 c
# 3 c