Distribute a vector randomly in an R data frame column

Viewed 110

I must be missing an obvious thing in R here.

I have a vector of say vec = c("v1","v2","v3") and I want to distribute this vector along a column in a data frame say

Girth   Height  Volume  newcolumn
8.3      70     10.3    V1
8.6      65     10.3    V2
8.8      63     10.2    V3
10.5     72     16.4    V1
10.7     81     18.8    V2
10.8     83     19.7    V3
11       66     15.6    V1
11       75     18.2    V2
10.8     83     19.7    V3
11       66     15.6    V1
11       75     18.2    V2
11.1     80     22.6    V3

Thanks in advance.

3 Answers

We can use rep to make sure that it would also work if the number of rows is not a multiple of 3

df$newcolumn <- rep(vec, length.out = nrow(df))

You'll need to somehow recycle values from vec.

cbind will do this, and produce your desired output

cbind(df, vec)
   Girth Height Volume vec
1    8.3     70   10.3  v1
2    8.6     65   10.3  v2
3    8.8     63   10.2  v3
4   10.5     72   16.4  v1
5   10.7     81   18.8  v2
6   10.8     83   19.7  v3
7   11.0     66   15.6  v1
8   11.0     75   18.2  v2
9   10.8     83   19.7  v3
10  11.0     66   15.6  v1
11  11.0     75   18.2  v2
12  11.1     80   22.6  v3

That said, your question title asks about "distribut[ing] a vector randomly". To do that you'll need

set.seed(123)
df$newcol <- sample (vec, size = nrow(df), replace = TRUE)
   Girth Height Volume newcol
   <dbl>  <dbl>  <dbl> <chr> 
 1   8.3     70   10.3 v3    
 2   8.6     65   10.3 v3    
 3   8.8     63   10.2 v3    
 4  10.5     72   16.4 v2    
 5  10.7     81   18.8 v3    
 6  10.8     83   19.7 v2    
 7  11       66   15.6 v2    
 8  11       75   18.2 v2    
 9  10.8     83   19.7 v3    
10  11       66   15.6 v1    
11  11       75   18.2 v2    
12  11.1     80   22.6 v2  
df$newcolumn <- vec

df

#>    Girth Height Volume newcolumn
#> 1    8.3     70   10.3        v1
#> 2    8.6     65   10.3        v2
#> 3    8.8     63   10.2        v3
#> 4   10.5     72   16.4        v1
#> 5   10.7     81   18.8        v2
#> 6   10.8     83   19.7        v3
#> 7   11.0     66   15.6        v1
#> 8   11.0     75   18.2        v2
#> 9   10.8     83   19.7        v3
#> 10  11.0     66   15.6        v1
#> 11  11.0     75   18.2        v2
#> 12  11.1     80   22.6        v3

This only works where the number of rows are a multiple of your vector length, taking advantage of vector recycling.

data

structure(list(Girth = c(8.3, 8.6, 8.8, 10.5, 10.7, 10.8, 11, 
11, 10.8, 11, 11, 11.1), Height = c(70L, 65L, 63L, 72L, 81L, 
83L, 66L, 75L, 83L, 66L, 75L, 80L), Volume = c(10.3, 10.3, 10.2, 
16.4, 18.8, 19.7, 15.6, 18.2, 19.7, 15.6, 18.2, 22.6)), class = "data.frame", row.names = c(NA, 
-12L))

vec <-  c("v1","v2","v3")

Created on 2020-05-24 by the reprex package (v0.3.0)

Related