将数据集的列批量更改为数字格式

4

我导入了一个Excel数据集,并希望在它们最初是字符时将近90个以上的列设置为数字。有什么最好的方法可以实现这一点,因为逐个导入并更改为数字不是最有效的方法吗?


1
你想在Excel中完成还是通过代码导入文件并在代码中进行更改? - STF
我犯了一个错误,我应该说明这是针对 R 的。我正在尝试导入 Excel 数据集,但它不会以数字形式出现,并且 stringsAsFactor = FALSE 似乎不起作用。 - D. Grayson
3
你可以使用sapply(foo.df, "as.numeric")将变量转换成数值形式。 - Akarsh Jain
2个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接