Adding Values to a New Column in a Dataframe by Index

Hello. All help is appreciated!

I know that I can create a new column in a dataframe and fill it with values. For example:

df$Day <- “Monday”

This will fill the newly added “Day” column with “Monday” for the extent of the dataframe.

How do I specify values by row index?

For example say that I want “Monday” for rows 1:3, “Tuesday” for rows 4:5, “Wednesday” for rows 6:10, etc.

If there is no pattern to the new column and no way to derive the value from an existing column, you would have to use something like the rep() function.

DF <- data.frame(Name = LETTERS[1:10])
DF$Day <- rep(c("Monday","Tuesday", "Wednesday"), c(3, 2, 5))
DF
   Name       Day
1     A    Monday
2     B    Monday
3     C    Monday
4     D   Tuesday
5     E   Tuesday
6     F Wednesday
7     G Wednesday
8     H Wednesday
9     I Wednesday
10    J Wednesday

This will work great for my purpose. Thank you!

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.