我正在尝试从数据框中提取数值,如下所示:
ID Secc col1 col2 col3
1 Sección 0805601006 1400 1300 85*
2 Sección 0805601007 1475 1365 5.0
3 Sección 0805601005 760 760 0.0
4 Sección 0805601003 1335 1335 0.0
5 Sección 0805601002 655 655 0.0
6 Sección 0805601004 900 815 85* 要获得仅包含数字字符的“干净”数据框,请执行以下操作:
ID Secc col1 col2 col3
1 0805601006 1400 1300 85
2 0805601007 1475 1365 5.0
3 0805601005 760 760 0.0
4 0805601003 1335 1335 0.0
5 0805601002 655 655 0.0
6 0805601004 900 815 85我已经尝试了很多函数,比如extract_numeric, st_replace, gsub等等,但是没有得到我想要的结果。
有人知道如何清理我的数据吗?
发布于 2018-08-17 20:09:44
您可以使用readr::parse_number:
library(readr)
df1[] <- lapply(df1, parse_number)
df1
# ID Secc col1 col2 col3
# 1 1 8.06e+08 1400 1300 85
# 2 2 8.06e+08 1475 1365 5
# 3 3 8.06e+08 760 760 0
# 4 4 8.06e+08 1335 1335 0
# 5 5 8.06e+08 655 655 0
# 6 6 8.06e+08 900 815 85
sapply(df1,class)
# ID Secc col1 col2 col3
# "numeric" "numeric" "numeric" "numeric" "numeric"在tidyspeak中,使用df1 %>% mutate_all(parse_number)
这是一种以R为基数的方法(相同的输出):
df1[] <-lapply(df1, function(x) as.numeric(gsub("(?![\\.-])\\D","",x, perl=T)))注意:tidyr::extract_numeric也可以工作,但是为了支持readr::parse_number,它被弃用了。
data
df1 <- read.table(text="ID Secc col1 col2 col3
1 'Sección 0805601006' 1400 1300 85*
2 'Sección 0805601007' 1475 1365 5.0
3 'Sección 0805601005' 760 760 0.0
4 'Sección 0805601003' 1335 1335 0.0
5 'Sección 0805601002' 655 655 0.0
6 'Sección 0805601004' 900 815 85*",h=T,strin=F) 发布于 2018-08-17 20:17:57
让我们考虑一种更通用的方法。数字可以是负数(-)。
我对数据进行了一些更改。
df1 <- read.table(text="ID Secc col1 col2 col3
1 'Sección 0805601006' 1400 1300 85*
2 'Sección 0805601007' -14rofl75 1365 5.0
3 'Sección 0805601005' 760 760 0.0
4 'Sección 0805601003' 1-3-3-5 1335 0.0
5 'Sección 0805601002' -655 HEHE-655 0.0
6 'Sección 0805601004' 900 815 85*",h=T,strin=F) 代码:
fun1 <- function(x) {
ge<-gregexpr("(^-?|(?<=\\D)-)?(\\d\\.?\\d*?)+",x,perl=T)
return(as.numeric(sapply(regmatches(x,ge),paste0,collapse="")))
}
df1[] <- lapply(df1,fun1)结果:
# ID Secc col1 col2 col3
#1 1 0805601006 1400 1300 85
#2 2 0805601007 -1475 1365 5
#3 3 0805601005 760 760 0
#4 4 0805601003 1335 1335 0
#5 5 0805601002 -655 -655 0
#6 6 0805601004 900 815 85https://stackoverflow.com/questions/51895089
复制相似问题