读取带有小数点的文件作为逗号在 R 坐标中不起作用?

Read file with decimals as comma not working in R cordinates?

我收到了一个 XY 坐标的字段,其中小数点作为逗号,但我无法在 R 中正确打开此文件。

我的数据应该是这样的 - 请注意逗号作为 y 坐标中的小数指示符:

"OBJECTID";"x_coord";"y_coord"
"1";"664936,3059";"5582773,2319"   # comma as separator
"2";"604996,5803";"5471445,4964"
"3";"772846,82";"5353980,45"
"4";"552181,8639";"5535271,7626"
"5";"604022,9011";"5470134,0649"

但是,在 read.csv 中指定 dec = ',' 只是将其读取为正常值:

xy <- read.delim(paste(path, "test_decimals2.txt", sep = '/'), 
               sep = '\t', dec = ",",skip = 0)

y 坐标缺少逗号分隔符:

  OBJECTID    x_coord     y_coord
1        1 6649363059 55827732319   # not a comma separator anymore
2        2 6049965803 54714454964
3        3   77284682   535398045
4        4 5521818639 55352717626
5        5 6040229011 54701340649

我试过将数据转成txt等,还是一样的问题。有人知道如何确保 dec = ',' 能正常工作吗?谢谢!

(坐标在 UTM 中,这就是它们看起来有点奇怪的原因)

a <- read.csv2("test_decimals2.txt", dec = ",", as.is = TRUE, header = FALSE, skip = 1)
a |> mutate(X = sub(",", ".", V2), Y = sub(",", ".", V3)) |>
  select(V1, X, Y)

我觉得read.csv2是欧式风格的答案csv-Data:

xy <- read.csv2(file = paste(path, "test_decimals2.txt", sep = '/'))

您的方法可能也是正确的。数据是正确的,只是在打印中没有显示足够的数字。

尝试打印您的数据:

> print.data.frame(xy, digits = 10)
  OBJECTID     x_coord     y_coord
1        1 664936.3059 5582773.232
2        2 604996.5803 5471445.496
3        3 772846.8200 5353980.450
4        4 552181.8639 5535271.763
5        5 604022.9011 5470134.065

这将打印限制为十位数字的数据帧。

添加到以前的答案。如果你想使用 read.delim() 功能,你可以简单地输入:

xy <- read.delim(file_path, sep = ';', skip = 0, dec = ",")

xy <- read.delim(file_path, sep = ';', skip = 0, colClasses = "character")
xy$x_coord <- as.numeric(gsub(",", ".", xy$x_coord))
xy$y_coord <- as.numeric(gsub(",", ".", xy$y_coord))

然后,您可以更改默认显示用途以打印更多数字:

options(digits = 12)

然后,打印 data.frame 会导致:

  OBJECTID     x_coord      y_coord
1        1 664936.3059 5582773.2319
2        2 604996.5803 5471445.4964
3        3 772846.8200 5353980.4500
4        4 552181.8639 5535271.7626
5        5 604022.9011 5470134.0649

我将数据复制到一个 txt 文件中,这对我来说效果很好:

read.csv2("test_decimals2.txt")

输出:

  OBJECTID  x_coord y_coord
1        1 664936.3 5582773
2        2 604996.6 5471445
3        3 772846.8 5353980
4        4 552181.9 5535272
5        5 604022.9 5470134

一种可能的方法:

testcommas <- read_delim(path,"\t", col_types=cols(.default="c"))
testcommas
# A tibble: 4 x 3
  item  coord_y coord_x
  <chr> <chr>   <chr>  
1 1     156,158 543,697
2 2     324,678 169,385
3 3     097,325 325,734
4 4     400,211 158,687

有了这个,所有的列都将是“字符”类型。然后你可以将它们更改为需要的数字if/as。一种方式:

testcommas <- data.frame(sapply(testcommas, function(x)  as.numeric(sub(",", ".", x, fixed = TRUE))))
testcommas
  item coord_y coord_x
1    1 156.158 543.697
2    2 324.678 169.385
3    3  97.325 325.734
4    4 400.211 158.687