gpt4 book ai didi

r - 在 R 中,如果数据框只有一列,为什么从数据框中选择行将数据作为向量返回?

转载 作者:行者123 更新时间:2023-12-04 17:12:12 24 4
gpt4 key购买 nike

假设我们要逐行访问数据帧中的数据。示例已简化,但在按行名称对数据框进行排序时,例如 (df[order(row.names(df)]),我们使用相同的技术。

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

> df
x1
a x
b y
c z

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

如果数据框有两列,我们会得到一个包含行名称的 1 行数据框:
> df
x1 x2
a x u
b y v
c z w

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

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

最佳答案

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

来自 ?"["

drop
For matrices and arrays. If TRUE the result is coerced to the lowest possible dimension (see the examples). This only works for extracting elements, not for the replacement. See drop for further details.


> 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 start 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

关于r - 在 R 中,如果数据框只有一列,为什么从数据框中选择行将数据作为向量返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7672152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com