3

The data frame looks like

y1 x2 x3 x4 x5
2  3  5   2  5
11 13 34  4  4
21 3  45  55 89

The study requires to add another column named x1 to this data.frame named x2 and fill all the observations with a particular string z. The output should look like :

y1 x1 x2 x3 x4 x5
2  z  3  5   2  5
11 z 13 34  4  4
21 z 3  45  55 89

Kindly help as I tried searching it on this forum but unable to find it.

akrun
  • 874,273
  • 37
  • 540
  • 662
gaurav kumar
  • 859
  • 2
  • 10
  • 24

1 Answers1

15

We can just assign the 'z'

df1$x1 <- 'z'

and then change the order of the columns,

df1[c(1, 6, 2:5)]

Or if this column needs to be created in a particular position, we can use append

data.frame(append(df1, c(x1='z'), after=1))
#  y1 x1 x2 x3 x4 x5
#1  2  z  3  5  2  5
#2 11  z 13 34  4  4
#3 21  z  3 45 55 89
akrun
  • 874,273
  • 37
  • 540
  • 662