user1477388
user1477388

Reputation: 21430

Can't get last column of data.frame

Consider the following data:

subjectName <- c("John Doe", "Jane Doe")
temperature <- c(98.1, 98.6)
gender <- factor(c('male', 'female'), levels = c('male','female'))

ptData <- data.frame(subjectName, temperature, gender, stringsAsFactors = F)

When I call:

ptData[,1]

I receive the first column, as expected. However, when I call:

ptData[,-1]

R fails to give me the last column. Instead, it outputs the last two:

  temperature gender
1        98.1   male
2        98.6 female

Why doesn't my call work as expected?

Upvotes: 0

Views: 1493

Answers (2)

rnso
rnso

Reputation: 24545

In python alist[-1] give last element but not in R. See Getting the last element of a list in Python

In addition to ptData[,ncol(ptData)], one can also use length function:

to get a list:

> ptData[,length(ptData)]
[1] male   female
Levels: male female

or to get a dataframe:

> ptData[length(ptData)]
  gender
1   male
2 female

Upvotes: 0

Stephan Kolassa
Stephan Kolassa

Reputation: 8267

ptData[,-1] gives you all columns except for the first. Try ptData[,ncol(ptData)] to get the last column.

(You may be confused about rows and columns... rows are indexed by the entry before the comma.)

Upvotes: 1

Related Questions