将数据集的列更改为数字

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

这应该如你所愿:

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

假设您的数据已经与所有字符列一起导入,您可以使用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 #> abcde #> <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 #> abcde #> <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 #> abcde #> <dbl> <chr> <dbl> <dbl> <dbl> #> 1 1 5 8 2 2 #> 2 2 6 9 3 3 #> 3 3 7 10 4 4