如何将数据帧列转换为数字类型?
当前回答
如果您不关心保留因子,并希望将其应用到任何可以转换为数字的列,我使用下面的脚本。 如果df是您的原始数据框架,您可以使用下面的脚本。
df[] <- lapply(df, as.character)
df <- data.frame(lapply(df, function(x) ifelse(!is.na(as.numeric(x)), as.numeric(x), x)))
顺便说一句,我参考了谢恩和乔兰的解决方案
其他回答
蒂姆是对的,谢恩有个遗漏。以下是其他例子:
R> df <- data.frame(a = as.character(10:15))
R> df <- data.frame(df, num = as.numeric(df$a),
numchr = as.numeric(as.character(df$a)))
R> df
a num numchr
1 10 1 10
2 11 2 11
3 12 3 12
4 13 4 13
5 14 5 14
6 15 6 15
R> summary(df)
a num numchr
10:1 Min. :1.00 Min. :10.0
11:1 1st Qu.:2.25 1st Qu.:11.2
12:1 Median :3.50 Median :12.5
13:1 Mean :3.50 Mean :12.5
14:1 3rd Qu.:4.75 3rd Qu.:13.8
15:1 Max. :6.00 Max. :15.0
R>
我们的data.frame现在有了因子列的摘要(counts)和as.numeric()的数值摘要(这是错误的,因为它得到了数值因子级别)以及as.numeric(as.character())的(正确的)摘要。
有一点对我很有帮助:如果要转换的变量范围(或者不止一个),可以使用sapply。
有点荒谬,举个例子:
data(cars)
cars[, 1:2] <- sapply(cars[, 1:2], as.factor)
假设第3列、第6-15列和第37列的数据帧需要转换为数字:
dat[, c(3,6:15,37)] <- sapply(dat[, c(3,6:15,37)], as.numeric)
虽然你的问题严格是关于数字的,但在开始r时,有许多转换是难以理解的。我将致力于解决帮助的方法。这个问题和这个问题类似。
在R中,类型转换可能是一种痛苦,因为(1)因子不能直接转换为数字,它们需要首先转换为字符类,(2)日期是一种特殊情况,通常需要单独处理,(3)跨数据帧列的循环可能很棘手。幸运的是,“潮流宇宙”已经解决了大部分问题。
This solution uses mutate_each() to apply a function to all columns in a data frame. In this case, we want to apply the type.convert() function, which converts strings to numeric where it can. Because R loves factors (not sure why) character columns that should stay character get changed to factor. To fix this, the mutate_if() function is used to detect columns that are factors and change to character. Last, I wanted to show how lubridate can be used to change a timestamp in character class to date-time because this is also often a sticking block for beginners.
library(tidyverse)
library(lubridate)
# Recreate data that needs converted to numeric, date-time, etc
data_df
#> # A tibble: 5 × 9
#> TIMESTAMP SYMBOL EX PRICE SIZE COND BID BIDSIZ OFR
#> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
#> 1 2012-05-04 09:30:00 BAC T 7.8900 38538 F 7.89 523 7.90
#> 2 2012-05-04 09:30:01 BAC Z 7.8850 288 @ 7.88 61033 7.90
#> 3 2012-05-04 09:30:03 BAC X 7.8900 1000 @ 7.88 1974 7.89
#> 4 2012-05-04 09:30:07 BAC T 7.8900 19052 F 7.88 1058 7.89
#> 5 2012-05-04 09:30:08 BAC Y 7.8900 85053 F 7.88 108101 7.90
# Converting columns to numeric using "tidyverse"
data_df %>%
mutate_all(type.convert) %>%
mutate_if(is.factor, as.character) %>%
mutate(TIMESTAMP = as_datetime(TIMESTAMP, tz = Sys.timezone()))
#> # A tibble: 5 × 9
#> TIMESTAMP SYMBOL EX PRICE SIZE COND BID BIDSIZ OFR
#> <dttm> <chr> <chr> <dbl> <int> <chr> <dbl> <int> <dbl>
#> 1 2012-05-04 09:30:00 BAC T 7.890 38538 F 7.89 523 7.90
#> 2 2012-05-04 09:30:01 BAC Z 7.885 288 @ 7.88 61033 7.90
#> 3 2012-05-04 09:30:03 BAC X 7.890 1000 @ 7.88 1974 7.89
#> 4 2012-05-04 09:30:07 BAC T 7.890 19052 F 7.88 1058 7.89
#> 5 2012-05-04 09:30:08 BAC Y 7.890 85053 F 7.88 108101 7.90
如果你遇到以下问题:
as.numeric(as.character(dat$x))
看看你的小数点。如果它们是“,”而不是“。”(如。"5,3")以上都不行。
一个潜在的解决方案是:
as.numeric(gsub(",", ".", dat$x))
我相信这在一些非英语国家是很常见的。
虽然其他人已经很好地讨论了这个话题,但我想补充一个额外的快速思考/提示。可以使用regexp提前检查字符是否可能仅由数字组成。
for(i in seq_along(names(df)){
potential_numcol[i] <- all(!grepl("[a-zA-Z]",d[,i]))
}
# and now just convert only the numeric ones
d <- sapply(d[,potential_numcol],as.numeric)
想要了解更多复杂的正则表达式,以及为什么要学习/体验它们的力量,请访问这个非常好的网站:http://regexr.com/