I am trying to remove some columns in a dataframe. I want to know why it worked for a single column but not with multible columns e.g. this works
我试图删除数据框中的一些列。我想知道为什么它适用于单个色谱柱但不适用于多色色谱柱,例如这很有效
album2[,5]<- NULL
this doesn't work
这不起作用
album2[,c(5:7)]<- NULL
Error in `[<-.data.frame`(`*tmp*`, , 5:7, value = NULL) :
replacement has 0 items, need 600
This also doesn't work
这也行不通
for (i in 5: (length(album2)-1)){
album2[,i]<- NULL
}
Error in `[<-.data.frame`(`*tmp*`, , i, value = NULL) :
new columns would leave holes after existing columns
3 个解决方案
#1
20
Basic subsetting:
album2 <- album2[, -5] #delete column 5
album2 <- album2[, -c(5:7)] # delete columns 5 through 7
#2
2
If you only want to remove columns 5 and 7 but not 6 try:
如果您只想删除第5列和第7列而不是第6列,请尝试:
album2 <- album2[,-c(5,7)] #deletes columns 5 and 7
#3
2
Adding answer as this was the top hit when searching for "drop multiple columns in r":
添加答案,因为这是搜索“在r中删除多个列”时的最高点:
The general version of the single column removal, e.g df$column1 <- NULL
, is to use list(NULL)
:
单列删除的一般版本,例如df $ column1 < - NULL,是使用list(NULL):
df[ ,c('column1', 'column2')] <- list(NULL)
df [,c('column1','column2')] < - list(NULL)
This also works for position index as well:
这也适用于位置索引:
df[ ,c(1,2)] <- list(NULL)
df [,c(1,2)] < - list(NULL)
This is a more general drop and as some comments have mentioned, removing by indices isn't recommended. Plus the familiar negative subset (used in other answers) doesn't work for columns given as strings:
这是一个更普遍的下降,正如一些评论所提到的,不推荐使用索引删除。另外,熟悉的否定子集(在其他答案中使用)对于作为字符串给出的列不起作用:
> iris[ ,-c("Species")]
Error in -"Species" : invalid argument to unary operator
#1
20
Basic subsetting:
album2 <- album2[, -5] #delete column 5
album2 <- album2[, -c(5:7)] # delete columns 5 through 7
#2
2
If you only want to remove columns 5 and 7 but not 6 try:
如果您只想删除第5列和第7列而不是第6列,请尝试:
album2 <- album2[,-c(5,7)] #deletes columns 5 and 7
#3
2
Adding answer as this was the top hit when searching for "drop multiple columns in r":
添加答案,因为这是搜索“在r中删除多个列”时的最高点:
The general version of the single column removal, e.g df$column1 <- NULL
, is to use list(NULL)
:
单列删除的一般版本,例如df $ column1 < - NULL,是使用list(NULL):
df[ ,c('column1', 'column2')] <- list(NULL)
df [,c('column1','column2')] < - list(NULL)
This also works for position index as well:
这也适用于位置索引:
df[ ,c(1,2)] <- list(NULL)
df [,c(1,2)] < - list(NULL)
This is a more general drop and as some comments have mentioned, removing by indices isn't recommended. Plus the familiar negative subset (used in other answers) doesn't work for columns given as strings:
这是一个更普遍的下降,正如一些评论所提到的,不推荐使用索引删除。另外,熟悉的否定子集(在其他答案中使用)对于作为字符串给出的列不起作用:
> iris[ ,-c("Species")]
Error in -"Species" : invalid argument to unary operator