Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

dataframe - In R, why does selecting rows from a data frame return data as a vector if the data frame has only one column?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

From ?"["

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])

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...