I have a data frame of the form
A = data.frame(c(1485,1486,1701,1808))
names(A) <- c("ID")
and a second data frame of the form
B = data.frame(1:12)
names(B) <- "value"
I want to be able to use this with rep
to form a second column in B such that I have
B$new <- rep(A,each = 3, length.out = 12)
giving
> B
value new
1 1 1485
2 2 1485
3 3 1485
4 4 1486
5 5 1486
6 6 1486
7 7 1701
8 8 1701
9 9 1701
10 10 1808
11 11 1808
12 12 1808
this works fine if I define A = c(1485,1486,1701,1808)
, but because A is a dataframe it does not. How do I convert A into the correct form to use with rep? I have tried as.list, as.vector, as.integer unsuccessfully.
As A
is a dataframe, you need to specify which column you want to repeat. (here ID
)
B$new <- rep(A$ID,each = 3, length.out = 12)
B
# value new
#1 1 1485
#2 2 1485
#3 3 1485
#4 4 1486
#5 5 1486
#6 6 1486
#7 7 1701
#8 8 1701
#9 9 1701
#10 10 1808
#11 11 1808
#12 12 1808
In your case, this would also work without using length.out
argument
rep(A$ID,each = 3)
It would repeat every ID
in A
3 times giving the same result.