最初にthis questionを参照しましたが、私の回答が役に立たなかった。R:文字列の先頭から先頭のゼロを削除する
私は、各コンポーネントに数字で始まり、単語(文字)で始まる要素が含まれているリストを持っています。要素の先頭の数字の一部には、1つ以上の先行ゼロがあります。ここでは、リストのごく一部です:私が達成したい何
x <- list(el1 = c("0010 First",
"0200 Second",
"0300 Third",
"4000 Fourth",
"0 Undefined",
"60838 Random",
"903200 Haphazard"),
el2 = c("0100 Hundredth",
"0200 Two hundredth",
"0300 Three hundredth",
"0040 Fortieth",
"0 Undefined",
"949848 Random",
"202626 Haphazard"),
el3 = c("0010 First",
"0200 Second",
"0300 Third",
"0100 Hundredth",
"0200 Two hundredth",
"0300 Three hundredth",
"0 Undefined",
"60838 Random",
"20200 Haphazard"))
は、彼らが利用可能であり、まだ0 Undefined
の始まりプラスで始まっていない他のすべての要素で、単一のゼロを持って先頭のゼロを削除することです先行ゼロ。それは次のようにリストを持って、次のとおりです。
x <- list(el1 = c("10 First",
"200 Second",
"300 Third",
"4000 Fourth",
"0 Undefined",
"60838 Random",
"903200 Haphazard"),
el2 = c("100 Hundredth",
"200 Two hundredth",
"300 Three hundredth",
"40 Fortieth",
"0 Undefined",
"949848 Random",
"202626 Haphazard"),
el3 = c("10 First",
"200 Second",
"300 Third",
"100 Hundredth",
"200 Two hundredth",
"300 Three hundredth",
"0 Undefined",
"60838 Random",
"20200 Haphazard"))
私は成功せず、今時間のために行くされています。私は何ができる最善のはこれです:しかし、それだけでなくても0 Undefined
せずに残りの部分を先行ゼロがあったリストの要素にこれらの要素を返しますが、ない
lapply(x, function(i) {
ifelse(grep(pattern = "^0+[1-9]", x = i),
gsub(pattern = "^0+", replacement = "", x = i), i)
})
。
誰かが助けることができますか?
の
pattern
とreplacement
引数を指定することができます!どうもありがとうございました! – panman'perl = TRUE'パラメータは省略できますが、実際には必要ありません。 'lapply(x、function(y)sub( '^ 0 +([1-9])'、 '\\ 1'、y))' – hwnd
@hwnd:ありがとう! – panman