我正在使用 read_csv 导入 csv。数据如下:
x <- rep("1306f",5)
y <- sample(1:10, 5)
df <- cbind(x,y)
df<-as.data.frame(df)
write.csv(df, "Desktop/names_test.csv")
当我使用
temp<-read_csv("Desktop/names_test.csv")
导入此内容时,第一列仅为“1306”。当我使用 temp<-read.csv("Desktop/names_test.csv)
导入时,我按预期得到“1306f”。
如果每行的最后一个字母不相同,如下所示:
x <- c("1306c","1306d","1306e","1306f","1306g")
y <- sample(1:10, 5)
df <- cbind(x,y)
df<-as.data.frame(df)
write.csv(df, "Desktop/names_test.csv")
使用
read_csv
导入时,我在第一列中获得了预期值,包括“f”。这种情况仅发生在该字母上(即,如果最后一个字母始终是 c,我会得到预期的结果)。
有什么想法吗?显然我可以只使用 read.csv,但希望继续使用 tidyverse。
readr 猜测列应该是字符类型,因此解决方案是更明确地说明列类型应该是什么。根据您的需要,有很多方法可以做到这一点,我建议查看
read_csv()
帮助页面 和 cols()
帮助页面
x <- rep("1306f",5)
y <- sample(1:10, 5)
df <- data.frame(x,y)
write.csv(df, "names_test.csv")
library(readr)
simple <- read_csv("names_test.csv")
#> New names:
#> Rows: 5 Columns: 3
#> ── Column specification
#> ──────────────────────────────────────────────────────── Delimiter: "," dbl
#> (3): ...1, x, y
#> ℹ Use `spec()` to retrieve the full column specification for this data. ℹ
#> Specify the column types or set `show_col_types = FALSE` to quiet this message.
#> • `` -> `...1`
# readr is 'guessing' the column should be a double
spec(simple)
#> cols(
#> ...1 = col_double(),
#> x = col_double(),
#> y = col_double()
#> )
explicit <- read_csv("names_test.csv", col_types = cols(x = col_character()))
#> New names:
#> • `` -> `...1`
spec(explicit)
#> cols(
#> ...1 = col_double(),
#> x = col_character(),
#> y = col_double()
#> )
explicit
#> # A tibble: 5 × 3
#> ...1 x y
#> <dbl> <chr> <dbl>
#> 1 1 1306f 5
#> 2 2 1306f 8
#> 3 3 1306f 10
#> 4 4 1306f 2
#> 5 5 1306f 4
创建于 2024-07-02,使用 reprex v2.1.0