1

I have a data frame "data" which has around 20 columns. Looks somewhat like :

Name Data1 Data2 Data3 Data4 Data5 ....
Fred   2     0     1     3    7  
Tim    2     3     6     5    6
Jack   3     1     1     2    6
Denise 4     5     0     2    8

I want to insert three columns "ID", "Age", "School" after the first column.

Is there anyway to do that?

I tried this :

ID<-''
Age<-''
School<-''
data<-cbind(data[,1], ID, Age, School, data[,2:ncol(data)])

It adds these columns but the first column becomes "data[,1]" and there is no way I can rename it.

gagolews
  • 12,836
  • 2
  • 50
  • 75
user1855888
  • 131
  • 2
  • 5

2 Answers2

2

Try this:

> data = read.table(header=T, text='Name Data1 Data2 Data3 Data4 Data5

Fred   2     0     1     3    7  
Tim    2     3     6     5    6
Jack   3     1     1     2    6
Denise 4     5     0     2    8')

> cbind(Name=data[,1], ID="", Age="", School="", data[,2:ncol(data)])

    Name ID Age School Data1 Data2 Data3 Data4 Data5
1   Fred                   2     0     1     3     7
2    Tim                   2     3     6     5     6
3   Jack                   3     1     1     2     6
4 Denise                   4     5     0     2     8
user1981275
  • 13,002
  • 8
  • 72
  • 101
1

Append can also do it.

dat <- read.table(text = "
Name Data1 Data2 Data3 Data4 Data5
Fred   2     0     1     3    7  
Tim    2     3     6     5    6
Jack   3     1     1     2    6
Denise 4     5     0     2    8", header = TRUE)

dat.new <- data.frame(append(dat, list(ID = "", age = ""), after =  2))
head(dat.new)
#    Name Data1 ID age Data2 Data3 Data4 Data5
#1   Fred     2            0     1     3     7
#2    Tim     2            3     6     5     6
#3   Jack     3            1     1     2     6
#4 Denise     4            5     0     2     8

We here use the fact that a data.frame is simply a list of vectors of equal length (almost).

Anders Ellern Bilgrau
  • 9,928
  • 1
  • 30
  • 37