本文介绍了在R中,如果数据帧只有一列,为什么从数据帧中选择行将数据作为向量返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们要逐行访问数据。这些例子是简化的,但是当按行名排序数据帧时,例如( df [order(row.names(df)] ),我们使用相同的技术。 / p>

如果数据框有一列,我们可以得到一个原子向量:

 > df 
x1
ax
by
cz

> df [1,]#返回原子向量
[1] x

如果数据框有两列,我们将返回一行1行数据框,其中包括行名:

 > df 
x1 x2
axu
byv
czw

> df [1,]#返回数据框
X1 X2
axu

我不明白为什么数据帧上的相同操作会产生两种类型的结果,具体取决于帧的多少列。

解决方案

这是因为 [的默认参数为 drop = TRUE



?[



 > dat1<  -  data.frame(x = letters [1:3])
> dat2< - data.frame(x = letters [1:3],y = LETTERS [1:3])

默认行为:

 > dat [1,] 
row sessionId scenarionName stepName duration
[1,] 1 1001 A开始0

> dat [2,]
row sessionId scenarionName stepName duration
[1,] 2 1001 A step1 2.2

使用 drop = FALSE

 > dat1 [1,,drop = FALSE] 
x
1 a

> dat2 [1,,drop = FALSE]
x y
1 a A


Suppose we want to access data from a data frame by row. The examples are simplified but when ordering a data frame by row names, for example, (df[order(row.names(df)]) we use the same technique.

If the data frame has one column, we get back an atomic vector:

> df
    x1
a   x
b   y
c   z

> df[1, ] # returns atomic vector
[1] x 

If the data frame has two columns, we get back a 1-row data frame including the row name:

> df
    x1 x2
a   x  u
b   y  v
c   z  w 

> df[1, ] # returns data frame
   X1 X2
a  x  u 

I don't understand why the same operation on the data frame yields two types of results depending on how many columns the frame has.

解决方案

It's because the default argument to [ is drop=TRUE.

From ?"["

> dat1 <- data.frame(x=letters[1:3])
> dat2 <- data.frame(x=letters[1:3], y=LETTERS[1:3])

The default behaviour:

> dat[1, ]
     row sessionId scenarionName stepName duration
[1,]   1      1001             A    start        0

> dat[2, ]
     row sessionId scenarionName stepName duration
[1,]   2      1001             A    step1      2.2

Using drop=FALSE:

> dat1[1, , drop=FALSE]
  x
1 a

> dat2[1, , drop=FALSE]
  x y
1 a A

这篇关于在R中,如果数据帧只有一列,为什么从数据帧中选择行将数据作为向量返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 10:43