Select column 2 to last column in R

2020-07-03 07:32发布

I have a data frame with multiple columns. Now, I want to get rid of the row.names column (column 1), and thus I try to select all the other columns.

E.g.,

newdata <- olddata[,2:10]

is there a default symbol for the last column so I don't have to count all the columns? I tried

newdata <- olddata[,2:]

but it didn't work.

3条回答
地球回转人心会变
2楼-- · 2020-07-03 08:17

To build on Freeman's answer, Tidyverse allows dots as replacement for the piped data object, which can be useful to simplify code with repetitive references to the object.

library(tidyverse)

newdata <- olddata %>% select( 2:ncol(.) )

or

newdata <- olddata %>% .[,2:ncol(.)]

查看更多
孤傲高冷的网名
3楼-- · 2020-07-03 08:25

I think it's better to focus on wanting to get rid of one column of data and not wanting to select every other column. You can do this as @Arun suggested:

olddata[,-1]

Or:

olddata$ColNameToDelete <- NULL
查看更多
男人必须洒脱
4楼-- · 2020-07-03 08:36

You can get the last column with ncol():

 newdata <- olddata[,2:ncol(olddata)]
查看更多
登录 后发表回答