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.
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
x_df$k[51:100] <- "y"
x_df
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)