简体   繁体   中英

Formatting a table in R with special symbols in columns

So I have run some analysis in R which I store in a data.frame() and at the end of the program I want to print a table for the user that is easy to read. I could just return the data frame to the user but I want to have column header names with space or special character (in particular I want there to be a percent sign). So my thought was that I could use the print() or paste() function to output a sort of table format.

So at the end of running the code I want the output to look exactly like the following:

     X       Y   P/E%
0.66120836 0.379 0.99
0.57320298 0.028 0.50
0.77160759 0.024 0.96
0.01532545 0.565 0.37
0.96046884 0.066 0.77

Here is some example code to generate the data I want to output:

x = runif(5)
y = round(runif(5),3)
z = round(runif(5),2)

Now I could use the data.frame() command but it won't allow me a column header like P/E% , for example

A = data.frame(X=x,Y=y,PE=z)

Because it won't like the / or the % sign. The closet thing I could think up to solve the problem is the following:

temp = paste("X","Y","P/E% \n",sep=" ")
for(i in 1:5){
    temp = paste(temp,paste(x[i],y[i],z[i],"\n",sep=" "),sep=" ")
}

but the spacing is weird if the column headers are long or the number of digits are different. If I go with the paste option, which I like, is there a way to make it so that the columns are aligned nicely no matter the shape of the data or number of digits? Like a left or right align?

Lastly, this code is going into an R shiny app and so it would be very nice to be able to solve this problem without having to have the user load a package to solve it.

Column names can have special symbols in them if they are quoted (if you disable validity checking of column names):

A = data.frame(X=x, Y=y, 'P/E%'=z, check.names=FALSE)

You then need to always use quotes with $ calls for access. $ accept any of the three types of quotes as long as they are matched:

a$`P/E%`

The "[[" function is designed to handle quoted arguments, but do not use backticks:

A[['P/E%']]

If you have an actual use case in mind, it needs to be presented more completely than just saying "needs to work with Shiny".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM