1

我有以下数据框(从 phyloseq 包中的 tax_table 对象转换而来)。

我怎样才能删除属性?

 str(DT2_mat)
'data.frame':   5120 obs. of  7 variables:
 $ : Factor w/ 2 levels "Archaea","Bacteria": 2 2 2 2 2 2 2 2 2 2 ...
  ..- attr(*, "names")= chr  "P11_16513" "P193_8942" "P187_9526" "P11_4543" ...
 $ : Factor w/ 28 levels "Acidobacteria",..: 2 2 2 2 2 2 2 2 2 2 ...
  ..- attr(*, "names")= chr  "P11_16513" "P193_8942" "P187_9526" "P11_4543" ...
 $ : Factor w/ 60 levels "Acidimicrobiia",..: 3 3 3 3 3 3 3 3 3 3 ...
  ..- attr(*, "names")= chr  "P11_16513" "P193_8942" "P187_9526" "P11_4543" ...
 $ : Factor w/ 108 levels "Acholeplasmatales",..: 29 29 29 29 29 29 29 29 29 29 ...
  ..- attr(*, "names")= chr  "P11_16513" "P193_8942" "P187_9526" "P11_4543" ...
 $ : Factor w/ 216 levels "0319-6A21","0319-6G20",..: 58 58 58 58 58 58 58 58 58 58 ...
  ..- attr(*, "names")= chr  "P11_16513" "P193_8942" "P187_9526" "P11_4543" ...
 $ : Factor w/ 699 levels "Abiotrophia",..: 173 173 173 173 173 173 173 173 173 173 ...
  ..- attr(*, "names")= chr  "P11_16513" "P193_8942" "P187_9526" "P11_4543" ...
 $ : Factor w/ 4964 levels "Abiotrophia defectiva Score:0.87",..: 1613 1529 1449 1448 1565 1438 1563 1532 1623 1605 ...
  ..- attr(*, "names")= chr  "P11_16513" "P193_8942" "P187_9526" "P11_4543" ...
P
4

2 回答 2

3

In general, you can remove attributes with the attr function by specifying the attribute you want to remove and setting it to NULL.

Suppose you get the following:

> str(my_df)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   107 obs. of  3 variables:
 $ case_no      : chr  "stuff" "more stuff" "other stuff" "residual stuff" ...
 $ region       : chr  "01" "02" "03" "04" ...
 $ petition     : chr  "RC" "RD" "RM" "RC" ...
 - attr(*, "label")= chr "NLRB7799"

You can remove the label with attr(my_df, "label") <- NULL

And get rid of unneeded extra classes by specifying the one you want with attr(my_df, "class") <- "data.frame"

This has worked well for me. Attributes tag along many times when importing data from other software like SAS or Stata. I dislike them because they give me trouble when merging or binding to other dataframes. Hopefully others will find this method useful.

于 2020-10-28T01:08:33.287 回答
1

实际上下降级别删除了所有属性。

> str(droplevels.data.frame(DT2_mat))
'data.frame':   5120 obs. of  7 variables:
 $ : Factor w/ 2 levels "Archaea","Bacteria": 2 2 2 2 2 2 2 2 2 2 ...
 $ : Factor w/ 28 levels "Acidobacteria",..: 2 2 2 2 2 2 2 2 2 2 ...
 $ : Factor w/ 60 levels "Acidimicrobiia",..: 3 3 3 3 3 3 3 3 3 3 ...
 $ : Factor w/ 108 levels "Acholeplasmatales",..: 29 29 29 29 29 29 29 29 29 29 ...
 $ : Factor w/ 216 levels "0319-6A21","0319-6G20",..: 58 58 58 58 58 58 58 58 58 58 ...
 $ : Factor w/ 699 levels "Abiotrophia",..: 173 173 173 173 173 173 173 173 173 173 ...
 $ : Factor w/ 4964 levels "Abiotrophia defectiva Score:0.87",..: 1613 1529 1449 1448 1565 1438 1563 1532 1623 1605 ...
于 2018-09-27T08:54:20.690 回答