从单列数据帧中删除行 [英] Remove rows from a single-column data frame

查看:167
本文介绍了从单列数据帧中删除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试从单个列数据框中删除最后一行时,我会得到一个向量而不是数据框:

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?

推荐答案

尝试添加 drop = FALSE 选项:

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

这篇关于从单列数据帧中删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆