[R] Read a txt file as numeric
arun
smartpink111 at yahoo.com
Thu Jul 11 13:54:13 CEST 2013
Hi,
May be this helps:
dat1<- read.table(text="
142,QUANTIZE_CAL_MIN_BAND_10,1
143,QUANTIZE_CAL_MAX_BAND_11,65535
144,QUANTIZE_CAL_MIN_BAND_11,1
145,END_GROUP,MIN_MAX_PIXEL_VALUE
146,GROUP,RADIOMETRIC_RESCALING
147,RADIANCE_MULT_BAND_1,1.2483E-02
148,RADIANCE_MULT_BAND_2,1.2730E-02
",sep=",",header=FALSE,stringsAsFactors=FALSE,row.names=1)
#Assuming that 142, 143, etc are row.names.
#You could create a new column with just the numeric values leaving the strings in the 2nd column.
dat1$NewCol<-as.numeric(ifelse(grepl("\\d+",dat1[,2]),dat1[,2],NA))
dat1[,2][grepl("\\d+",dat1[,2])]<-NA
dat1
# V2 V3 NewCol
#142 QUANTIZE_CAL_MIN_BAND_10 <NA> 1.0000e+00
#143 QUANTIZE_CAL_MAX_BAND_11 <NA> 6.5535e+04
#144 QUANTIZE_CAL_MIN_BAND_11 <NA> 1.0000e+00
#145 END_GROUP MIN_MAX_PIXEL_VALUE NA
#146 GROUP RADIOMETRIC_RESCALING NA
#147 RADIANCE_MULT_BAND_1 <NA> 1.2483e-02
#148 RADIANCE_MULT_BAND_2 <NA> 1.2730e-02
str(dat1)
#'data.frame': 7 obs. of 3 variables:
# $ V2 : chr "QUANTIZE_CAL_MIN_BAND_10" "QUANTIZE_CAL_MAX_BAND_11" "QUANTIZE_CAL_MIN_BAND_11" "END_GROUP" ...
# $ V3 : chr NA NA NA "MIN_MAX_PIXEL_VALUE" ...
# $ NewCol: num 1 65535 1 NA NA ...
A.K.
Hello,
I am relatively new to the R community.
I have a .txt file containing the metafile with informations
regarding landsat calibration parameters. This contains 2 columns: one
with the description of the parameter and the other one with the value
of the parameter. The problem is that the column with the values
contains also words in some cases, which I believe makes the
read.table() read the column not as a numeric value.
This is an example of how it looks like:
142 QUANTIZE_CAL_MIN_BAND_10 1 142
143 QUANTIZE_CAL_MAX_BAND_11 65535 143
144 QUANTIZE_CAL_MIN_BAND_11 1 144
145 END_GROUP MIN_MAX_PIXEL_VALUE 145
146 GROUP RADIOMETRIC_RESCALING 146
147 RADIANCE_MULT_BAND_1 1.2483E-02 147
148 RADIANCE_MULT_BAND_2 1.2730E-02 148
149 RADIANCE_MULT_BAND_3 1.1656E-02 149
I need the left column to be read as numeric, does anyone have some good suggestion on how to approach this problem?
Thank you in advance.
Stefano
More information about the R-help
mailing list