2017-09-17 1 views
4

私はExcelデータセットをインポートしており、最初の文字である場合、ほぼすべての列(90以上)を数値に設定したいと考えています。これを達成するための最善の方法は、それぞれを1つずつ数値にインポートして変更するのが最も効率的な方法ではないからです。データセットの列を数値に変更する

+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 
関連する問題