0

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?

flodel
  • 87,577
  • 21
  • 185
  • 223
user1477388
  • 20,790
  • 32
  • 144
  • 264

2 Answers2

1

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.)

Stephan Kolassa
  • 7,953
  • 2
  • 28
  • 48
  • Yes, I know how to do it. `ptData[,ncol(ptData)]` will give me the last column. But, I am more curious as to why my code doesn't work as expected. If `ptData[,1]` gives the me first column, then why doesn't `ptData[,-1]` give me the last? For example, look at this vector `v <- c(1,2)` `v[-1] # outputs 2` – user1477388 Nov 04 '14 at 14:06
  • 1
    @user1477388 It does work as documented. Read `help("[")` and adjust you expectations. – Roland Nov 04 '14 at 14:08
  • As @AnandaMahto explains, `foo[,c(i,j)]` will give you columns `i` and `j`... whereas `foo[,-c(i,j)]` will give you all columns *except for columns `i` and `j`* (if both `i` and `j` are positive integers). You may have misunderstood something... – Stephan Kolassa Nov 04 '14 at 14:09
  • @user1477388, your vector example only works because the vector has only two elements: removing the first element in that case results in only the last element being returned/left. Try the same with more than 2 elements in a vector. – talat Nov 04 '14 at 14:09
0

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
Community
  • 1
  • 1
rnso
  • 23,686
  • 25
  • 112
  • 234