Adding a new column and give it 2 separate values

So, I currently added a new column to my dataframe. Now, I am needing to make the first 50 rows carry the value of "x" and the second 50 rows carry the value of "y."

My code so far is:

x_df$k <- c("x", "y")

Which gives me a new column but alternates the x and y values until it reaches 100.

So, I tried to do:

x_df$k <- head(x_df$k["x" = 50], tail(x_df$k["y" = 50]))

But, this gives me all "y" values for my k column.. Any tips are greatly appreciated

Ok so after over an hour of trial and error, I accidentally got it!

For anyone who may need this tip or for anyone who may see a better way of doing this and/or can explain the logic to me (since I got my result by accident). Please, chime in.

My code:

x_df$k[1:50] <- "x"
x_df$k[51:100] <- "y"

If you want to add the column in one step, you can use the rep() function. It repeats a given vector a given number of times. The repetitions can be done with the elements repeating sequentially with each element repeated n times and then the next element. Compare the output of the following two calls.

rep(c("x", "y"), 4)
rep(c("x", "y"), each = 4)

To get what you want, try

#invent a data frame
DF <- data.frame(A = 101:200)

#Make a new column
DF$k <- rep(c("x", "y"), each = 50)

That's, honestly, pretty neat. One day, these more efficient and effective solutions are going to come to me more naturally!

This topic was automatically closed 7 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.