无法获取data.frame的最后一列

时间:2022-07-20 21:05:24

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:

R没有给我最后一栏。相反,它输出最后两个:

  temperature gender
1        98.1   male
2        98.6 female

Why doesn't my call work as expected?

为什么我的电话不按预期工作?

2 个解决方案

#1


1  

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

ptData [, - 1]为您提供除第一列之外的所有列。尝试使用ptData [,ncol(ptData)]获取最后一列。

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

(您可能会对行和列感到困惑...行被逗号前的条目索引。)

#2


0  

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

在python alist [-1]中给出最后一个元素但不在R中。请参阅在Python中获取列表的最后一个元素

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

除了ptData [,ncol(ptData)]之外,还可以使用length函数:

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

#1


1  

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

ptData [, - 1]为您提供除第一列之外的所有列。尝试使用ptData [,ncol(ptData)]获取最后一列。

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

(您可能会对行和列感到困惑...行被逗号前的条目索引。)

#2


0  

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

在python alist [-1]中给出最后一个元素但不在R中。请参阅在Python中获取列表的最后一个元素

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

除了ptData [,ncol(ptData)]之外,还可以使用length函数:

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