문제

I would like to limit the number of decimals when a data frame is imported. My .txt input have 16 decimals to each row in collumn "Value". In a same collumns it can have numbers and strings, at same time. My dataframe look like that:

Value 

0.202021561664556
0.202021561664556
0.202021561664556
0.202021561664556
NC
...

My expected dataframe

Value
0.20202156
0.20202156
0.20202156
0.20202156
NC
...

Real input (DF) that not works:

DF <- "NE001358.Log.R.Ratio
    -0.0970369274475688
    0.131893549586039
    0.0629266495860389
    0.299559132381831
    -0.0128804337656807
    0.0639743960526874
    0.0271669351886552
    0.322395363972391
    0.179591292893632
            NC"

DF <- read.table(text=DF, header = TRUE)
도움이 되었습니까?

해결책

You can use substring on character vectors to cut them down. Here we take only the first ten characters in the string.

> DF
##               Value
## 1 0.202021561664556
## 2 0.202021561664556
## 3 0.202021561664556
## 4 0.202021561664556
## 5                NC

> DF$Value <- substring(DF$Value, 1, 10)
> DF
##        Value
## 1 0.20202156
## 2 0.20202156
## 3 0.20202156
## 4 0.20202156
## 5         NC

But since these are log ratios, they should really be numeric. In your DF data at the bottom of your post, you could wrap substring in as.numeric and NA values will replace "NC" entries.

> DF[,1] <- as.numeric(substring(DF[,1], 1, 10))

다른 팁

You can do this with as.numeric and format:

num <- as.numeric(as.character(DF[,1]))
ifelse(is.na(num), DF[,1], format(num, nsmall=8))
#  [1] "-0.09703693" " 0.13189355" " 0.06292665" " 0.29955913" "-0.01288043" " 0.06397440" " 0.02716694"
#  [8] " 0.32239536" " 0.17959129" "NC"

If you wanted to limit significant digits instead of digits after the decimal place, you should use the digits option instead of nsmall. If you don't like the leading space at the beginning of numbers, use trim=TRUE.

How about this:

DF$NE001358.Log.R.Ratio <- as.character(DF$NE001358.Log.R.Ratio)
DFn <- suppressWarnings(as.numeric(DF[,1]))
DF[!is.na(DFn),] <- format(DFn,nsmall=8)[!is.na(DFn)]
DF         
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top