【问题标题】:Mass changing columns of a data set to numeric将数据集的列批量更改为数字
【发布时间】:2017-09-19 01:20:18
【问题描述】:

我已经导入了一个 Excel 数据集,并且想要将几乎所有列(大于 90)设置为数字,当它们最初是字符时。实现这一点的最佳方法是什么,因为逐个导入并更改为数字并不是最有效的方法?

【问题讨论】:

  • 你想在excel中做还是通过代码导入文件并且你想在你的代码中进行更改?
  • 我的错误,我应该指定这是针对 R 的。我正在尝试导入一个 excel 数据集,但它不会以数字形式出现,并且 stringsAsFactor = FALSE 似乎不起作用.
  • 您可以使用sapply(foo.df, "as.numeric") 将变量转换为数值形式。

标签: r excel


【解决方案1】:

这应该如你所愿:

# Random data frame for illustration (100 columns wide)
df <- data.frame(replicate(100,sample(0:1,1000,rep=TRUE)))

# Check column names / return column number (just encase you wanted to check)
colnames(df)

# Specify columns
cols <- c(1:length(df))   # length(df) is useful as if you ever add more columns at later date

# Or if only want to specify specific column numbers: 
# cols <- c(1:100) 

#With help of magrittr pipe function change all to numeric
library(magrittr)
df[,cols] %<>% lapply(function(x) as.numeric(as.character(x)))

# Check our columns are numeric
str(df)

【讨论】:

    【解决方案2】:

    假设您的数据已经与所有字符列一起导入,您可以使用mutate_at 按位置或名称将相关列转换为数字:

    suppressPackageStartupMessages(library(tidyverse))  
    
    # Assume the imported excel file has 5 columns a to e
    df <- tibble(a = as.character(1:3),
                 b = as.character(5:7),
                 c = as.character(8:10),
                 d = as.character(2:4),
                 e = as.character(2:4))
    
    # select the columns by position (convert all except 'b')
    df %>% mutate_at(c(1, 3:5), as.numeric)
    #> # A tibble: 3 x 5
    #>       a     b     c     d     e
    #>   <dbl> <chr> <dbl> <dbl> <dbl>
    #> 1     1     5     8     2     2
    #> 2     2     6     9     3     3
    #> 3     3     7    10     4     4
    
    # or drop the columns that shouldn't be used ('b' and 'd' should stay as chr)
    df %>% mutate_at(-c(2, 4), as.numeric)
    #> # A tibble: 3 x 5
    #>       a     b     c     d     e
    #>   <dbl> <chr> <dbl> <chr> <dbl>
    #> 1     1     5     8     2     2
    #> 2     2     6     9     3     3
    #> 3     3     7    10     4     4
    
    # select the columns by name
    df %>% mutate_at(c("a", "c", "d", "e"), as.numeric)
    #> # A tibble: 3 x 5
    #>       a     b     c     d     e
    #>   <dbl> <chr> <dbl> <dbl> <dbl>
    #> 1     1     5     8     2     2
    #> 2     2     6     9     3     3
    #> 3     3     7    10     4     4
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-02
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      • 2013-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多