gpt4 book ai didi

从 readr::read_csv 中读取的数据中删除属性

转载 作者:行者123 更新时间:2023-12-03 23:14:08 25 4
gpt4 key购买 nike

readr::read_csv添加在编辑数据时不会更新的属性。例如,

library('tidyverse')
df <- read_csv("A,B,C\na,1,x\nb,1,y\nc,1,z")

# Remove columns with only one distinct entry
no_info <- df %>% sapply(n_distinct)
no_info <- names(no_info[no_info==1])

df2 <- df %>%
select(-no_info)

检查结构,我们看到 B 列仍然存在于 df2 的属性中。 :
> str(df)
Classes ‘spec_tbl_df’, ‘tbl_df’, ‘tbl’ and 'data.frame': 3 obs. of 3 variables:
$ A: chr "a" "b" "c"
$ B: num 1 1 1
$ C: chr "x" "y" "z"
- attr(*, "spec")=
.. cols(
.. A = col_character(),
.. B = col_double(),
.. C = col_character()
.. )
> str(df2)
Classes ‘spec_tbl_df’, ‘tbl_df’, ‘tbl’ and 'data.frame': 3 obs. of 2 variables:
$ A: chr "a" "b" "c"
$ C: chr "x" "y" "z"
- attr(*, "spec")=
.. cols(
.. A = col_character(),
.. B = col_double(),
.. C = col_character()
.. )
> attributes(df2)
$class
[1] "spec_tbl_df" "tbl_df" "tbl" "data.frame"

$row.names
[1] 1 2 3

$spec
cols(
A = col_character(),
B = col_double(),
C = col_character()
)

$names
[1] "A" "C"

>

如何删除列(或对数据的任何其他更新)并使更改准确反射(reflect)在新数据结构和属性中?

最佳答案

您可以通过将其设置为 NULL 来删除列规范:

> attr(df, 'spec') <- NULL
> str(df)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 3 obs. of 3 variables:
$ A: chr "a" "b" "c"
$ B: int 1 1 1
$ C: chr "x" "y" "z"
> df
# A tibble: 3 x 3
A B C
<chr> <int> <chr>
1 a 1 x
2 b 1 y
3 c 1 z

关于从 readr::read_csv 中读取的数据中删除属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54000753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com