我正在读取csv文件中的数据,数据中的一列有三种不同的格式:
xxxxx-xxx-xx (5-3-2)
xxxxx-xxxx-x (5-4-1)
xxxx-xxxx-xx (4-4-2)
我的目标是将这三种不同的风格转换为以下形式: xxxxx-xxxx-xx(5-4-2)
为了使所有不同的形式相同,我需要在3个不同条件中的每个条件的特定位置插入额外的零,如下所示:
xxxxx-0xxx-xx
xxxxx-xxxx-0x
0xxxx-xxxx-xx
有人对最佳方法有所了解吗?
答案 0 :(得分:8)
我会使用sprintf
和strsplit
:
x <- c('11111-111-11', '11111-1111-1', '1111-1111-11')
y <- strsplit(x, '-')
myfun <- function(y) {
first <- sprintf('%05d', as.integer(y[1]))
second <- sprintf('%04d', as.integer(y[2]))
third <- sprintf('%02d', as.integer(y[3]))
paste(first, second, third, sep='-')
}
sapply(y, myfun)
# [1] "11111-0111-11" "11111-1111-01" "01111-1111-11"
您也可以使用花哨的正则表达式或gsubfn
包来执行此操作,但这可能有点过头了!
答案 1 :(得分:5)
Justin解决方案的编程版本略短且功能更强大
numbers <- c('11111-111-11', '11111-1111-1', '1111-1111-11')
restyle <- function(number, fmt){
tmp <- as.list(as.integer(strsplit(number, '-')[[1]]))
do.call(sprintf, modifyList(tmp, list(fmt = fmt)))
}
sapply(numbers, restyle, fmt = '%05d-%04d-%02d', USE.NAMES = F)
答案 2 :(得分:3)
您是否在类似unix的环境中工作?在命令行而不是R的正则表达式函数中使用sed可能更容易。
echo "54324-965-23" | sed 's/\(.....\)-\(...\)-\(..\)/\1-0\2-\3/'
将吐回来
54324-0965-23
如果要将其应用于整个文件,它看起来像
cat file1.txt | sed 's/\(.....\)-\(...\)-\(..\)/\1-0\2-\3/' > file2.txt
如果你有多个txt更改操作,你可以将它们一起管道
cat file1.txt | sed 's/\(.....\)-\(...\)-\(..\)/\1-0\2-\3/' | sed '2ndthing' | sed 'thirdthing' > file2.txt
答案 3 :(得分:0)
对此的一个解决方案是首先删除连字符,然后将它们添加回所需的字符位置,如下所示:
> v <- c("01234-567-89","01234-5678-9","0123-4567-89")
> v
[1] "01234-567-89" "01234-5678-9" "0123-4567-89"
> #remove hyphens
> v <- gsub("-","",v)
> v
[1] "0123456789" "0123456789" "0123456789"
> #add hyphens
> paste(substr(v,1,4),substr(v,5,8),substr(v,9,10),sep="-")
[1] "0123-4567-89" "0123-4567-89" "0123-4567-89"