【问题标题】:DPLYR: Convert multiple columns from character to integerDPLYR:将多列从字符转换为整数
【发布时间】:2020-10-12 18:31:10
【问题描述】:

我正在使用长表,但需要将其(部分)转换为宽表以使用 Vegan 统计包中的数据。但是,当我使用 pivot-wider 函数时,所有列都以字符结尾。我找不到如何将列(以科学物种名称作为标题)转换为整数的解决方案。我已经阅读了很多帖子,但到目前为止所有解决方案都不起作用。我用来创建表格的代码:

biota_C <- (biota_species) %>%
  ungroup() %>% 
  select(Species, Station, Numbers) %>%
  pivot_wider(names_from = Station, values_from = Numbers) %>%
  t() %>%
  row_to_names(row_number = 1)

除了数据类型之外,结果表对我来说看起来不错。Species table

> glimpse(biota_C)
 chr [1:306, 1:27] "0" "1" "0" " 0" " 1" " 2" "1" "2" "0" "4" "0" "0" "0" "0" "0" "3" "0" "1" "0" "0" "0" " 0" ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:306] "X00A2" "X00A4" "X00A6" "X00B2" ...
  ..$ : chr [1:27] "Aphelochaeta marioni" "Arenicola marine" "Aricidea minuta" "Bathyporeia saris" ...

显然我忽略了一些东西。

最好的,贝瑞

【问题讨论】:

    标签: r dplyr type-conversion integer character


    【解决方案1】:

    您使用 row.names 转置了整个 data.frame,因此所有内容都转换为字符。

    试试这样的:

    df = data.frame(Species = rep(c("Aphelochaeta marioni","Arenicola marine","Aricidea minuta","Bathyporeia saris"),each=5),
    Station=rep(letters[1:5],4),Numbers=rpois(20,20))
    
    df %>% 
    pivot_wider(names_from = Station, values_from = Numbers) %>%
    column_to_rownames("Species") %>% 
    t() %>% glimpse()
    
     int [1:5, 1:4] 15 19 19 22 27 25 20 21 17 23 ...
     - attr(*, "dimnames")=List of 2
      ..$ : chr [1:5] "a" "b" "c" "d" ...
      ..$ : chr [1:4] "Aphelochaeta marioni" "Arenicola marine" "Aricidea minuta" "Bathyporeia saris"
    

    【讨论】:

      【解决方案2】:

      看表的图片,可以看到species表中多了一些空格,所以这个表中的列都是字符。您可以使用dplyr 中的mutate_allas.numeric 来转换类型:

      biota_C <- biota_C %>% 
        mutate_all(as.numeric)
      

      【讨论】:

      • 谢谢。这会产生或多或少相同的错误:UseMethod("tbl_vars") 中的错误:没有适用于 'tbl_vars' 的方法应用于类“c('matrix', 'character')”的对象
      【解决方案3】:

      我们可以在dplyr 1.0.0 中使用acrossmutate

      library(dplyr)
      biota_C <- biota_C  %>%
                    mutate(across(everything(), as.numeric))
      

      【讨论】:

      • 谢谢。我试过了,但我得到一个错误: UseMethod("mutate_") 中的错误:没有适用于 'mutate_' 的方法应用于类 "c('matrix', 'character')" 的对象
      • @BerryvanderHoorn 如果你有一个matrix 对象,然后用as.data.frame 转换为data.frameas.data.frame(biota_C) %&gt;% mutate(..
      • 这工作 akrun,非常感谢!显然,转置数据会将其转换为矩阵。我会考虑到这一点。
      猜你喜欢
      • 1970-01-01
      • 2013-04-01
      • 2018-07-31
      • 2017-02-03
      • 1970-01-01
      • 1970-01-01
      • 2018-04-15
      • 2021-01-01
      • 2015-01-14
      相关资源
      最近更新 更多