# example data
df <- structure(c(-1, 0, 0, -1, -1, 2), .Dim = 2:3)
# how it looks like
df
r$> df
[,1] [,2] [,3]
[1,] -1 0 -1
[2,] 0 -1 2
# construct a data.frame using two rows of df
data.frame(df[1:2, ])
r$> data.frame(df[1:2,])
X1 X2 X3
1 -1 0 -1
2 0 -1 2
# construct a data.frame using only one row of df
data.frame(df[1, ])
r$> data.frame(df[1, ])
df.1...
1 -1
2 0
3 -1
data.frame(df[1:2,]) has the same structure as df, but data.frame(df[1, ]) has not.
Is it possible to let data.frame(df[1, ]) create a data frame with only one row, but not one column?
CodePudding user response:
Let us call the input m instead of df because it is a matrix and not a data.frame.
When indexing a matrix there is an optional drop= argument which defaults to TRUE which means that the result of a scalar index will be to drop the dimensions and so convert the result to an ordinary vector. drop has no effect if the index has length > 1. In that case we always get a matrix. Stated in another way by default or if drop = TRUE then we get a vector if the index is scalar and a matrix otherwise. If drop = FALSE then we always get a matrix result. Thus, specify that drop=FALSE.
m <- structure(c(-1, 0, 0, -1, -1, 2), .Dim = 2:3)
m[1, ] # vector
## [1] -1 0 -1
m[1,, drop = TRUE] # same
## [1] -1 0 -1
m[1,, drop = FALSE] # matrix
## [,1] [,2] [,3]
## [1,] -1 0 -1
m[1:2,, drop = FALSE] # matrix
## [,1] [,2] [,3]
## [1,] -1 0 -1
## [2,] 0 -1 2
Now when we apply data.frame we get a single row.
data.frame( m[1,, drop = FALSE] )
## X1 X2 X3
## 1 -1 0 -1
data.frame(m[1:2,, drop = FALSE])
## X1 X2 X3
## 1 -1 0 -1
## 2 0 -1 2
If we already have a vector so that it is too late to use drop = FALSE then we can use rbind to turn it into a matrix.
data.frame(rbind(m[1, ]))
## X1 X2 X3
## 1 -1 0 -1
data.frame(rbind(m[1:2, ]))
## X1 X2 X3
## 1 -1 0 -1
## 2 0 -1 2
CodePudding user response:
A possible solution:
df <- structure(c(-1, 0, 0, -1, -1, 2), .Dim = 2:3)
data.frame(t(df[1, ]))
#> X1 X2 X3
#> 1 -1 0 -1
CodePudding user response:
The issue is that selecting just one row from a matrix returns a vector, not a matrix:
str(df[1:2, ])
#> num [1:2, 1:3] -1 0 0 -1 -1 2
str(df[1, ])
#> num [1:3] -1 0 -1
You would have to turn it into a matrix again, to get your expected behavior:
df[1, ] |>
matrix(nrow = 1) |>
data.frame()
#> X1 X2 X3
#> 1 -1 0 -1
Created on 2022-02-05 by the reprex package (v2.0.1)
