我在文本文件中有一组值 -
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
现在我在R -
中导入这些值mydata = read.table("D:/tmp/mlclass-ex1-005/mlclass-ex2-005/R-Studio/ex2data1.txt",header=TRUE,sep=",");
但是在导入时我想在十进制之后只用2个值格式化值
34.62365962451697,78.0246928153624,0
将作为
加载34.62,78.02,0
我知道我应该运行“格式”来做必要但是如何在导入自己的同时实现同样的目标。 或者格式化mydata的另一种方法是什么,因为如果我尝试运行
format(round(mydata,2),nsmall=2)
它会抛出错误 -
Error in Math.data.frame(list(test1 = c(9L, 2L, 11L, 38L, 73L, 19L, 41L, :
non-numeric variable in data frame: test1test2
阅读后我的数据结构
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 ...
答案 0 :(得分:1)
如果您的data.frame不是所有数字,您可以使用以下内容:
mydata[] <- lapply(mydata, function(x) {if (is.numeric(x)) round(x, 2) else x})
答案 1 :(得分:0)
也许我误解了这个问题,但在我看来
mydata = read.table("D:/tmp/mlclass-ex1-005/mlclass-ex2-005/R-Studio/ex2data1.txt",header=TRUE,sep=",");
mydata=round(mydata,2)
应该做什么?