8

I have data

       N11.1 N22.2 N33.1 N44.1 N21.1 N31.1 N32.1
Sinus      1     0     0   0.0     0     0  12.0
ArrAHB     1     0     0   0.1     0     0  20.9

where I want to add an extra column ID with values Sinus and ArrAHB.

require(lattice)
Sinus<-c(1,0,0,0,0,0,12)
ArrAHB<-c(1,0,0,0.1,0,0,20.9)
Labels<-c("N11.1","N22.2","N33.1","N44.1","N21.1","N31.1","N32.1")
ID<-c("Sinus","Arr/AHB")
data.female<-data.frame(Sinus,ArrAHB,row.names=Labels)
data.female<-t(data.female)

> data.female$ID<-ID

Warning message:
In data.female$ID <- ID : Coercing LHS to a list

Why does the creation of the ID column cause the coercion in the data.frame?

P.s. My goal is to get this data to the form like here for barchart(N11.1+N22.1+N33.1+N44.1+N21.1+N31.1+N32.1 ~ ID, data=data.female) which requires a new ID column here, I cannot understand why this ID addition sometimes works and sometimes not. Please explain.

Community
  • 1
  • 1
hhh
  • 50,788
  • 62
  • 179
  • 282
  • 3
    `t` returns a matrix. You can't use `$<-` to assign into a matrix. Thus R coerces the matrix into a list. You are probably approaching this in a suboptimal way, but I'm not sure how the plot is supposed to look like and thus can't suggest a good alternative. – Roland Nov 18 '16 at 16:22

2 Answers2

22

It's throwing a warning, as the results of transpose t() are a matrix. Matricies don't have accessible column names. You have to coerce the matrix to a data frame before you make the ID assignment, using as.data.frame()

This works.

Sinus<-c(1,0,0,0,0,0,12)
ArrAHB<-c(1,0,0,0.1,0,0,20.9)
Labels<-c("N11.1","N22.2","N33.1","N44.1","N21.1","N31.1","N32.1")
ID<-c("Sinus","Arr/AHB")
data.female<-data.frame(Sinus,ArrAHB,row.names=Labels)
data.female<-as.data.frame(t(data.female))

data.female$ID<-ID

Remember that data frames are defined column-wise and not row-wise. A data frame definition should be by columns.

Jake Kaupp
  • 7,892
  • 2
  • 26
  • 36
4

I know this is late but I ran across the same problem. You can do this:

data.female <- cbind(data.female, ID)
Denis
  • 11,796
  • 16
  • 88
  • 150