Converting specific cells of data frame to table in R

℡╲_俬逩灬. 提交于 2019-12-11 10:23:40

问题


I have a data frame (read from RDS file) with 140 variables. I have subsetted 3 of them. But the subset has only one row with three column variables. I have to present it as a table and make a bar chart too. The subset data frame looks like this.

HomeCondn_Good    HomeCondn_Livabl    HomeCondn_Dilapdtd
       (dbl)            (dbl)              (dbl)
1      65.9             29.7                4.3

The reproducible example is as follows:

structure(list(HomeCondn_Good = 65.9, HomeCondn_Livabl = 29.7, 
                HomeCondn_Dilapdtd = 4.3), .Names = c("HomeCondn_Good", "HomeCondn_Livabl", 
                                                      "HomeCondn_Dilapdtd"), class = c("tbl_df", "data.frame"), row.names = c(NA, 
                                                                                                                              -1L))

I want to convert this into a table in the following format:

   Parameter           Proportion
1 HomeCondn_Good        65.9
2 HomeCondn_Livabl      29.7
3 HomeCondn_Dilapdtd     4.3

I tried reshape package and used melt function. (Assuming 'home' is the name of the object)

Home <- melt(Home)
names(Home)[1] <- "Parameter"
names(Home)[2] <- "Proportion"

I am getting the following warning:

No id variables; using all as measure variables

I am implementing this in Shiny, While I am getting the desired table output, this clearly impacts other components of the program which either not giving the output or just not rendering. Can someone help me understand this please?


回答1:


We can use gather from tidyr

library(tidyr)
gather(df1, Parameter, Proportion)
#              Parameter Proportion
#               (fctr)      (dbl)
#1     HomeCondn_Good       65.9
#2   HomeCondn_Livabl       29.7
#3 HomeCondn_Dilapdtd        4.3


来源:https://stackoverflow.com/questions/34066576/converting-specific-cells-of-data-frame-to-table-in-r

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