Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply parentheses around elements of R dataframe

Tags:

r

Apologies for the basic question but I am very new to R. I have a two row dataframe that I will export to Latex and am trying to amend the second (currently numeric) row so that it retains 4 decimal places and is encased in parentheses.

Is this possible?

Current dataframe: df:

  col1   |   col2   |   col3
-------------------------------
 0.0553     0.1354     0.1403
 0.0000     0.0956     0.9110

Desired dataframe:

  col1   |   col2   |   col3
-------------------------------
 0.0553     0.1354     0.1403
(0.0000)   (0.0956)   (0.9110)
like image 958
malligator Avatar asked Apr 26 '15 21:04

malligator


People also ask

How is [] used in R?

The square brackets are used for indexing into a vector, matrix, array, list or dataframe. You can think of the square brackets as marking the edges of a cell, column or row of a table. The square brackets are also called extraction operators as they are used to extract specific elements from a vector or matrix.

What is the difference between parentheses and brackets in R?

Parentheses are for functions, brackets are for indicating the position of items in a vector or matrix. (Here, items with numbers like x1 are user-supplied variables.)

How do you subset data in R with brackets?

You can subset a column in R in different ways: If you want to subset just one column, you can use single or double square brackets to specify the index or the name (between quotes) of the column. Specifying the indices after a comma (leaving the first argument blank selects all rows of the data frame).

What is bracket notation in R?

R has a notation system that lets you extract values from R objects. To extract a value or set of values from a data frame, write the data frame's name followed by a pair of hard brackets: deck [ , ]


1 Answers

Try

df1[2,] <- paste0("(", format(unlist(df1[2,])),")")
df1
#     col1     col2     col3
#1   0.0553   0.1354   0.1403
#2  (0.0000) (0.0956) (0.9110)

data

df1 <- structure(list(col1 = c(0.0553, 0), col2 = c(0.1354, 0.0956), 
col3 = c(0.1403, 0.911)), .Names = c("col1", "col2", "col3"
 ), class = "data.frame", row.names = c(NA, -2L))
like image 132
akrun Avatar answered Sep 19 '22 12:09

akrun