如何删除所有属性?

时间:2018-12-05 07:39:40

标签: r attr

我想从数据中删除所有属性并应用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"

4 个答案:

答案 0 :(得分:5)

要删除所有属性,该如何处理

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

答案 1 :(得分:1)

提供的所有列都是相同的类型(如您的示例中所示)

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

答案 2 :(得分:0)

PKPDmisc软件包具有dplyr友好的方式来做到这一点:

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

答案 3 :(得分:0)

稍微简化一下@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

(原答案由布赖恩·里普利教授在https://r.789695.n4.nabble.com/function-to-remove-attributes-td914615.html

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)]