R: `ID : Coercing LHS to a list` in adding an ID column, why?

空扰寡人 提交于 2020-07-08 13:32:05

问题


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.


回答1:


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.




回答2:


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

data.female <- cbind(data.female, ID)


来源:https://stackoverflow.com/questions/40681628/r-id-coercing-lhs-to-a-list-in-adding-an-id-column-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!