2017-09-17 21 views
4

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

+1

你想在Excel中做到这一点,或者你通过代码导入文件,你想在你的代码中进行更改? – STF

+0

我的错误,我应该指定这是为R.我试图导入一个Excel数据集,但它不会作为数字和stringsAsFactor = FALSE似乎不工作。 –

+3

您可以使用'sapply(foo.df,“as.numeric”)'将变量转换为数字形式。 –

回答

0

这应该做你的愿望:

# 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) 
0

假设您的数据已经与所有字符列进口的,你可以把相关列的位置或名称中使用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 
相关问题