R语言 如何删除所有属性?

23c0lvtd  于 2023-01-06  发布在  其他
关注(0)|答案(6)|浏览(161)

我想删除所有属性从数据和应用this solution。但无论是one_entry()(原来的)和我的one_entry2()将工作,我不明白为什么。

one_entry2 <- function(x) {
  attr(x, "label") <- NULL
  attr(x, "labels") <- NULL
}

> lapply(df1, one_entry2)
$`id`
NULL

$V1
NULL

$V2
NULL

$V3
NULL

我们如何才能做到这一点?

  • 数据:*
df1 <- setNames(data.frame(matrix(1:12, 3, 4)), 
                c("id", paste0("V", 1:3)))
attr(df1$V1, "labels") <- LETTERS[1:4]
attr(df1$V1, "label") <- letters[1:4]
attr(df1$V2, "labels") <- LETTERS[1:4]
attr(df1$V2, "label") <- letters[1:4]
attr(df1$V3, "labels") <- LETTERS[1:4]
attr(df1$V3, "label") <- letters[1:4]

> str(df1)
'data.frame':   3 obs. of  4 variables:
 $ id: int  1 2 3
 $ V1: int  4 5 6
  ..- attr(*, "labels")= chr  "A" "B" "C" "D"
  ..- attr(*, "label")= chr  "a" "b" "c" "d"
 $ V2: int  7 8 9
  ..- attr(*, "labels")= chr  "A" "B" "C" "D"
  ..- attr(*, "label")= chr  "a" "b" "c" "d"
 $ V3: int  10 11 12
  ..- attr(*, "labels")= chr  "A" "B" "C" "D"
  ..- attr(*, "label")= chr  "a" "b" "c" "d"
p5fdfcr1

p5fdfcr11#

要删除 * 所有 * 属性,请执行以下操作

df1[] <- lapply(df1, function(x) { attributes(x) <- NULL; x })
str(df1)
#'data.frame':  3 obs. of  4 variables:
# $ id: int  1 2 3
# $ V1: int  4 5 6
# $ V2: int  7 8 9
# $ V3: int  10 11 12
lnlaulya

lnlaulya2#

简化一点@maurits-evers回答:

df1[] <- lapply(df1, as.vector)
str(df1)
#'data.frame':  3 obs. of  4 variables:
# $ id: int  1 2 3
# $ V1: int  4 5 6
# $ V2: int  7 8 9
# $ V3: int  10 11 12

最初的答案是Brian Ripley教授在this R-Help post中给出的。
tidyverse世界中:

df1 <- df1 %>% mutate(across(everything(), as.vector))

带有data.table

library(data.table)
# Assuming
# setDT(df1) # or
# df1 <- as.data.table(df1)

df1 <- df1[, lapply(.SD, as.vector)]
dohp0rv5

dohp0rv53#

如果所有列都是相同类型(如示例中所示),则可以执行以下操作

df1[] = c(df1, recursive=TRUE)
svmlkihl

svmlkihl4#

PKPDmisc包有一个dplyr友好的方法来实现这一点:

library(PKPDmisc)
df %>% strip_attributes(c("label", "labels"))
vbkedwbf

vbkedwbf5#

以下是一个简单的解决方案(并且不会将日期类转换为数字):

df1 <- data.frame(df1)
bxgwgixi

bxgwgixi6#

在某些情况下,@maurits-evers的修改版本可能会有用。
创建一个函数来移除属性。

remove_attributes <- function(x) {attributes(x) <- NULL; return(x)}

从列表中的一个元素中删除属性。

df1$V1 <- remove_attributes(df1$V1)

从列表中的所有元素中删除属性。

df1 <- lapply(df1, remove_attributes)

相关问题