assign row name while rbind a row in a data frame

空扰寡人 提交于 2019-12-10 12:24:23

问题


I want to assign a rowname (A_B) while I rbind a row into a new dataframe (d). The row is the result of the ratio of two rows of another data frame (df).

    df <- data.frame(ID = c("A", "B" ),replicate(3,sample(1:100,2,rep=TRUE)))
    d <- data.frame()
    d<-rbind(d, df[df$ID == "A",2:4 ]/df[df$ID == "B", 2:4])

Actual output

    X1   X2   X3
1 0.08 0.14 0.66

Expected output. Instead of rowname 1 I want A_B as result of A_B ratio

       X1   X2   X3
A_B 0.08 0.14 0.66

回答1:


updated the solution to address multiple rows

You can workaround for the desired row names from following solution....

df <- data.frame(ID = c("A", "B" ),replicate(3, sample(1:100,8,rep=TRUE)))
# This is where you control what you like to see as the row names    
rownames(df) <- make.names( paste("NAME", df[ ,"ID"]) , unique = TRUE)
d <- data.frame()
rbind(d, df[df$ID == "A",2:4 ]/df[df$ID == "B", 2:4], make.row.names = "T")

output

               X1        X2         X3
NAME.A   0.8690476 1.1851852 2.40909091
NAME.A.1 1.8181818 0.8095238 1.01408451
NAME.A.2 0.8235294 5.4444444 2.50000000
NAME.A.3 1.4821429 1.8139535 0.05617978



回答2:


Maybe it's a stupid solution, but have you tried give it directly the row name? Some like this:

rbind(d, your_name = (df[df$ID == "A",2:4 ]/df[df$ID == "B", 2:4]))

For me it's working... Regards.



来源:https://stackoverflow.com/questions/41982549/assign-row-name-while-rbind-a-row-in-a-data-frame

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