How to get the first row of a dataframe with names when there is only one column?
When extracting a dataframe using [
by default drop
argument is TRUE
.
From ?Extract
drop - If TRUE the result is coerced to the lowest possible dimension.
Also you can check the class for both the dataframe after extracting the row.
df1 = data.frame(A=c(12,13), B=c(24,25))
df2 = data.frame(A=c(12,13))
class(df1[1, ])
#[1] "data.frame"
class(df2[1, ])
#[1] "numeric"
As we can see df2
is coerced to a vector. Using drop = FALSE
will keep it as dataframe and not drop the dimensions.
df2[1,, drop = FALSE]
# A
#1 12
class(df[1,, drop = FALSE])
#[1] "data.frame"
From dplyr
?slice
Choose rows by their ordinal position
library(dplyr)
slice(df, 1L)
# A
#1 12
str(slice(df, 1L))
# 'data.frame': 1 obs. of 1 variable:
#$ A: num 12
If you want it to be a named number, you can unlist
it.
str(unlist(slice(df, 1L)))
#Named num 12
# - attr(*, "names")= chr "A"
You can as well transpose it keeping column names.
colnames(t(unlist(slice(df, 1L))))
#"A"
If you want a named vector, then a single column data frame can be tricky to extract. A potential workaround can be,
do.call(c, df)[1]
#A1
#12
Where,
str(do.call(c, df)[1])
Named num 12
- attr(*, "names")= chr "A1"
Note that since it converts all the values to named vector, it adds a numeric suffix after the name so it does not have duplicated names