Remove rows from a single-column data frame

怎甘沉沦 提交于 2019-12-18 06:11:29

问题


When I try to remove the last row from a single column data frame, I get a vector back instead of a data frame:

> df = data.frame(a=1:10)
> df
    a
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10 10

> df[-(length(df[,1])),]
[1] 1 2 3 4 5 6 7 8 9

The behavior I'm looking for is what happens when I use this command on a two-column data frame:

> df = data.frame(a=1:10,b=11:20)
> df
    a  b
1   1 11
2   2 12
3   3 13
4   4 14
5   5 15
6   6 16
7   7 17
8   8 18
9   9 19
10 10 20

> df[-(length(df[,1])),]
  a  b
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
6 6 16
7 7 17
8 8 18
9 9 19

My code is general, and I don't know a priori whether the data frame will contain one or many columns. Is there an easy workaround for this problem that will let me remove the last row no matter how many columns exist?


回答1:


Try adding the drop = FALSE option:

R> df[-(length(df[,1])), , drop = FALSE]
  a
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9


来源:https://stackoverflow.com/questions/3232557/remove-rows-from-a-single-column-data-frame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!