【问题标题】:How to erase all attributes?如何清除所有属性?
【发布时间】:2019-05-06 17:33:51
【问题描述】:

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

【问题讨论】:

  • 如果有人需要从一个数字变量中删除所有属性,这对我有用:as.numeric(a)

标签: r attr


【解决方案1】:

要删除所有属性,这个怎么样

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

【讨论】:

  • 亲爱的 Maurits,请问df1[] 到底在这里做什么?我以前从未遇到过这种结构。提前致谢。
  • 嗨@AnoushiravanR。与其说我做得不好,不如改写别人说得更好,看看here
  • 非常感谢您的回复和链接。不,你在这里做得很好:)祝你好运。
【解决方案2】:

如果所有列都是相同的类型(如您的示例),您可以这样做

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      简化一点@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 的 Brian Ripley 教授提供)

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

      【讨论】:

      • 我认为您的 tidyverse 答案应该是当前公认的答案.....干净简单,谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      • 1970-01-01
      • 2016-12-22
      • 1970-01-01
      • 2010-10-29
      • 1970-01-01
      • 2014-01-27
      相关资源
      最近更新 更多