R create tibble row with NA with data type dbl

Viewed 350

How can I create one row in tibble format with data type as <dbl>?

(not <lgl> as in the example below)

NAs <- rep(NA, 10)
NAs1 <- t(tibble(NAs))
NAs2 <- as_tibble(NAs1)
NAs2

# # A tibble: 1 x 10
#   V1    V2    V3    V4    V5    V6    V7    V8    V9    V10  
#   <lgl> <lgl> <lgl> <lgl> <lgl> <lgl> <lgl> <lgl> <lgl> <lgl>
# 1 NA    NA    NA    NA    NA    NA    NA    NA    NA    NA   

thanks in advance.

3 Answers

You can use t over NAs before using as_tibble, e.g.,

> tibble::as_tibble(`class<-`(t(NAs),"numeric"))
# A tibble: 1 x 10
     V1    V2    V3    V4    V5    V6    V7    V8    V9   V10
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA

You can use NA_real_ to specify the type of NA.

tibble::as_tibble(t(rep(NA_real_, 10)))

# # A tibble: 1 x 10
#      V1    V2    V3    V4    V5    V6    V7    V8    V9   V10
#   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA

From ?NA:

NA is a logical constant of length 1 which contains a missing value indicator. NA can be coerced to any other vector type except raw. There are also constants NA_integer_, NA_real_, NA_complex_ and NA_character_ of the other atomic vector types which support missing values: all of these are reserved words in the R language.

We can also use tibble_row

library(tibble)
as_tibble_row(setNames(rep(NA_real_, 10), paste0("V", 1:10)))
# A tibble: 1 x 10
#     V1    V2    V3    V4    V5    V6    V7    V8    V9   V10
#  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA
Related