Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subsetting Vector not returning desired values

Tags:

r

vector

x <- c(1.0,1.1,2.5,3.5)

x[1] returning 1 as the output

instead I want 1.0 as the output.

like x[2] returns 1.1 as the output.

like image 633
gadia-aayush Avatar asked Jul 30 '26 21:07

gadia-aayush


1 Answers

As Sathish said in comment you have to set format:

x <- c(1.0,1.1,2.5,3.5)
x[1]
[1] 1

cat(format(x[1],nsmall = 1)
1.0

However, your vector is still numeric. I used cat() only for display the number:

x[1] + x[2]
[1] 2.1

x[1:2]
[1] 1.0 1.1

So if you want to display single element of vector (with .0) I'll recommend cat and format.

Of course you can do something like this:

x <- format(x,nsmall = 1)
x[1]
[1] "1.0"

But your vector is now character instead of numeric, so be careful with formatting numbers in R.

Summarizing, you have to change format if you want to display the number with decimal separator and 0, I mean single number. But don't format whole data, use it only for this case.

like image 178
Adamm Avatar answered Aug 02 '26 10:08

Adamm