'change data.frame() behavior

# 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?



Solution 1:[1]

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

Solution 2:[2]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PaulS
Solution 2 shs