Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting a repeating value into a column

Tags:

r

I feel dumb asking this but here goes. I have a list of numbers but I want to combine it with date.

for instance:

list1 <- c(1, 2, 3, 4, 5)
list2 <-c("2009-01-01")
list3 <-cbind(list2, list1)

I want the SAME date listed the same number of times as there are data points and then combined with the data points.

date                number
"2009-01-01"          1
"2009-01-01"          2
"2009-01-01"          3
"2009-01-01"          4
"2009-01-01"          5

When I try to run the above code I get the message about lengths not matching. Any suggestions are appreciated. Thanks.

like image 323
acesnap Avatar asked Aug 23 '11 14:08

acesnap


People also ask

How do I add a column to a repeating value in R?

How to repeat column values in R data frame by values in another column? First of all, create a data frame. Then, use rep function along with cbind function to repeat column values in the matrix by values in another column.

How do you repeat a value in R?

In R, the easiest way to repeat rows is with the REP() function. This function selects one or more observations from a data frame and creates one or more copies of them. Alternatively, you can use the SLICE() function from the dplyr package to repeat rows.

How do you repeat rows in a Dataframe?

repeat(3) will create a list where each index value will be repeated 3 times and df. iloc[df. index. repeat(3),:] will help generate a dataframe with the rows as exactly returned by this list.


2 Answers

Edited to make my data frame comment more descriptive.

How about using rep?

list1 <- 1:5
list2 <- rep("2009-01-01",length(list1))
list3 <- cbind(list2, list1)

although R's recycling rules ought to give you your desired output regardless. Also, are you sure you don't want a data frame:

list3 <- data.frame(date = list2, number = list1)

since cbind will in your case produce a character matrix, which, since matrices must only be of a single type.

like image 149
joran Avatar answered Sep 28 '22 19:09

joran


cbind will return a dataframe if one of the arguments is a dataframe. In that case, it simply acts as a wrapper for data.frame [see ?cbind].

In the other answers and comments where the users said that cbind did work and it created a matrix, they left out that the matrix was a character matrix and the numbers were coalesced to character strings. You probably didn't want that.

One solution, not presented yet, is to do this:

vector1 <- c(1, 2, 3, 4, 5);
vector2 <- c("2009-01-01");
cbind(data.frame(date = vector2), number = vector1);

This creates a dataframe because the first argument is a dataframe.

But, I think the best, and the one that really shows that you know what you want is to call data.frame directly:

data.frame(date = vector2, number = vector1);
like image 32
adamleerich Avatar answered Sep 28 '22 20:09

adamleerich