Reputation: 8385
I have a set of values in text file-
34.62365962451697,78.0246928153624,0
30.28671076822607,43.89499752400101,0
35.84740876993872,72.90219802708364,0
60.18259938620976,86.30855209546826,1
79.0327360507101,75.3443764369103,1
45.08327747668339,56.3163717815305,0
Now I am importing these values in R-
mydata = read.table("D:/tmp/mlclass-ex1-005/mlclass-ex2-005/R-Studio/ex2data1.txt",header=TRUE,sep=",");
But while importing I want to format the values with only 2 values after decimal means
34.62365962451697,78.0246928153624,0
will be loaded as
34.62,78.02,0
I know I should run "format" to do the needful but how can I achieve the same while importing itself. or what is the other way out to format mydata because if I try to run
format(round(mydata,2),nsmall=2)
it throws the error-
Error in Math.data.frame(list(test1 = c(9L, 2L, 11L, 38L, 73L, 19L, 41L, :
non-numeric variable in data frame: test1test2
Structure of my data after reading
str(mydata)
'data.frame': 100 obs. of 3 variables:
$ test1 : Factor w/ 100 levels "30.05882244669796",..: 9 2 11 38 73 19 41 65 68 83 ...
$ test2 : Factor w/ 100 levels "30.60326323428011",..: 72 15 62 80 66 36 95 21 83 14 ...
$ admitted: int 0 0 0 1 1 0 1 1 1 1 ...
Upvotes: 0
Views: 2186
Reputation: 132706
If your data.frame isn't all numbers, you can use something like this:
mydata[] <- lapply(mydata, function(x) {if (is.numeric(x)) round(x, 2) else x})
Upvotes: 1
Reputation: 517
Maybe I misunderstand the question, but it seems to me that
mydata = read.table("D:/tmp/mlclass-ex1-005/mlclass-ex2-005/R-Studio/ex2data1.txt",header=TRUE,sep=",");
mydata=round(mydata,2)
should do the trick ?
Upvotes: 0