Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将单个或多个空格替换为单个/多个零_R - Fatal编程技术网

R 将单个或多个空格替换为单个/多个零

R 将单个或多个空格替换为单个/多个零,r,R,最后,我想将该值转换为.numeric,但在此之前,我想将空格替换为零。我在这里执行两步sub,因为我当时只能执行单个空格。可以用一个命令来完成吗 x <- c(' 3','1 2','12 ') ## could be leading, trailing or in the mid x as.numeric(x) ## <@><< NAs introduced by coercion x <- sub(' ','0',sub(' ',

最后,我想将该值转换为.numeric,但在此之前,我想将空格替换为零。我在这里执行两步
sub
,因为我当时只能执行单个空格。可以用一个命令来完成吗

x <- c('  3','1 2','12 ')    ## could be leading, trailing or in the mid
x
as.numeric(x)      ## <@><<    NAs introduced by coercion
x <- sub(' ','0',sub(' ','0',x))
as.numeric(x)

x此方法可以将所有前导空格替换为前导0

# Load package
library(stringr)

# Create example strings with leading white space and number
x <- c("  3", "    4", "    12")

x %>%
  # Trim the leading white space
  str_trim(side = "left") %>%
  # Add leading 0, the length is based on the original stringlength
  str_pad(width = str_length(x), side = "left", pad = "0")

#[1] "003"    "00004"  "000012"
而且它不必引导空白区域。以OP的更新为例

x <- c('  3','1 2','12 ')
gsub(" ", "0", x)
#[1] "003" "102" "120"

x将前导零添加到整数有什么意义?将
作为.numeric(x)
有什么错?(仅供参考
sub('\\s+','00',x)
)是的,只需按.numeric(x)的方式执行,即可删除所有空格do
gsub('\\s','',x)
。Sotos提供的内容将用零替换遇到的第一个零序列(例如,如果x使用格式选项,它不会替换第一个非空字符后面的空格(请参阅):
x谢谢大家,我不想破坏对齐,因为它的结构非常复杂,是逻辑上的0,1,2,3s,我通过子字符串(x,120122)引用我的值,+我需要保留它以备审核。因此,理想情况下,我只想将空格替换为零。我修改了我的示例,使其更真实,因此.numeric将在其上中断。对于其他计算,它将按照所有人的建议工作。Tx M
x <- c('  3','1 2','12 ')
gsub(" ", "0", x)
#[1] "003" "102" "120"