gadia-aayush
gadia-aayush

Reputation: 53

Subsetting Vector not returning desired values

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.

Upvotes: 3

Views: 117

Answers (1)

Adamm
Adamm

Reputation: 2306

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.

Upvotes: 4

Related Questions