tibble columns must have consistent length

I am trying to create a tibble with a continuous and a factor variable.

library(tibble)
library(forcats)
df <- tibble(value = rnorm(100, 100, 0.5), type = as_factor(c("1", "2", "3")))
#> Error: Tibble columns must have consistent lengths, only values of length one are recycled:
#> * Length 3: Column `type`
#> * Length 100: Column `value`

How do I fix this?

As it says in the error message, you're creating columns of two different lengths. The three arguments you've specified to rnorm() are matched by position to the rnorm() arguments:

rnorm(n, mean = 0, sd = 1)

Where: n number of observations. If length(n) > 1 , the length is taken to be the number required.

So you have one vector/column that's of length 100, and another that's of length 3.

Unlike with base data frames, tibble does not automatically recycle vectors to match length, hence the error.

If you meant to create a value column with the three values you specified to rnorm() it would look like the first example in the reprex below. You could also use rnorm() with n set to 99, and repeat your factor variable 33 times, which would give them matching lengths (the second example below).

library(tibble)
library(forcats)

df <- tibble(value = c(100, 100, 0.5), type = as_factor(c("1", "2", "3")))

df
#> # A tibble: 3 x 2
#>   value type 
#>   <dbl> <fct>
#> 1 100   1    
#> 2 100   2    
#> 3   0.5 3

df <- tibble(value = rnorm(99, 100, 0.5), type = rep(as_factor(c("1", "2", "3")), 33))

df
#> # A tibble: 99 x 2
#>    value type 
#>    <dbl> <fct>
#>  1  99.6 1    
#>  2 101.  2    
#>  3 101.  3    
#>  4 101.  1    
#>  5 101.  2    
#>  6  99.9 3    
#>  7  99.1 1    
#>  8  99.4 2    
#>  9  99.4 3    
#> 10  99.9 1    
#> # … with 89 more rows

Created on 2019-04-22 by the reprex package (v0.2.1)

3 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.