Amber
Amber

Reputation: 31

Adding a New Column with an Increment in R

I am trying to add a new column to the beginning of my data frame in R. Right now I have something that looks like

a b c d
1 2 3 4
1 2 3 4
4 1 6 3

and I want to add a new column, z, that adds by 5 in each row to get something like

z a b c d
5 1 2 3 4
10 1 2 3 4
15 4 1 6 3

Upvotes: 3

Views: 5093

Answers (2)

Minions
Minions

Reputation: 1313

declare your new z vector by say z <- c(5,10,15) or using another way if it follows a particular pattern. After initialization use the cbind function to merge it with the original dataframe.

cbind(df,z) adds the new vector at the end and cbind(z,df) adds in the beginning. since u want it at the beginning u can use cbind(z,df)

Upvotes: 2

akrun
akrun

Reputation: 887501

Try

z<- seq(5, length.out=nrow(df1), by=5)

Or

z <- 5*seq_len(nrow(df1))
cbind(z, df1)
#   z a b c d
#1  5 1 2 3 4
#2 10 1 2 3 4
#3 15 4 1 6 3

Upvotes: 5

Related Questions