【问题标题】:rep() Function Using a Variable for 'times' is Throwing an Error使用“times”变量的rep()函数抛出错误
【发布时间】:2016-09-20 20:17:27
【问题描述】:

我有数据集(比如)test:

test <- data.frame(x = c(90, 801, 6457, 92727), y = rep("test", 4))
print(test)
      x    y
1    90 test
2   801 test
3  6457 test
4 92727 test

我想创建反映test$x 的变量test$z,除了test$z 总是10 个字符长,用零填充空白。所以生成的数据框看起来像:

print(test)
      x    y          z
1    90 test 0000000090
2   801 test 0000000801
3  6457 test 0000006457
4 92727 test 0000092727

我认为下面的函数会给我想要的结果:

test$z <- paste0(as.character(rep(0, 10-nchar(as.character(test$x)))), as.character(test$x))

但它会在rep 函数中回退以下错误:

rep(0, 10 - nchar(as.character(test$x))) 中的错误:
'times' 参数无效

我有什么想法可以用 rep 函数或任何其他解决方案来获得test$z 吗?

【问题讨论】:

  • 你可以使用 sprintf。
  • formatC(test$x, flag = '0', digits = 10, width = 10)

标签: r


【解决方案1】:

问题源于rep(0, 10-nchar(as.character(test$x))),其中第二个参数是一个向量,即times 参数。基本上,这会引发错误:

rep(0, c(9, 8, 7, 4))

相反,您应该这样做:

rep(c(0,0,0,0), c(9, 8, 7, 4))

其中两个向量的长度相同。

?rep 声明:

如果时间由单个整数组成,则结果由重复此多次的整个输入组成。如果times是一个与x长度相同的向量(被每个复制后),结果由x[1]次重复[1]次,x[2]次重复[2]次等组成。

在我们的示例中,xc(0,0,0,0)timesc(9, 8, 7, 4)

你可以这样做:

test$z <- sapply(test$x, function(x) paste0(paste0(rep(0,10-nchar(x)),collapse = ""),x))

#      x    y          z
#1    90 test 0000000090
#2   801 test 0000000801
#3  6457 test 0000006457
#4 92727 test 0000092727

【讨论】:

    【解决方案2】:

    在 cmets @Roland 中提到了 sprintf(),这是一个好主意。 @m0h3n 在他的回答中用 rep() 解释了这个问题。这是两者的替代方案。

    您可以将rep() 替换为新的基本函数strrep(),这将回收其x 参数times 的长度。它似乎很适合您的情况。

    strrep(0, 10 - nchar(test$x))
    # [1] "00000000" "0000000"  "000000"   "00000"   
    

    所以我们只需将其粘贴到test$x 的前面即可。不需要任何as.character 强制,因为这一切都是在内部完成的。

    paste0(strrep(0, 10 - nchar(test$x)), test$x)
    # [1] "0000000090" "0000000801" "0000006457" "0000092727"
    

    注意:strrep() 是在 R 版本 3.3.1 中引入的。

    【讨论】:

      【解决方案3】:

      到目前为止,您有几个很好的答案。

      为了好玩,这里有一个使用您可能已经知道的功能的“快速而肮脏”的方法示例。

      test$z <- substr(paste0('0000000000', as.character(test$x)),
                       nchar(test$x),
                       10+nchar(test$x))
      

      只需将比您需要的更多的零 (例如,10) 粘贴到每个条目和子字符串中。

      附:您可以将上述代码中的零字符串替换为长度为 n 的字符串,方法是:

      paste0(rep(0, n), collapse='')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-09
        • 2020-02-03
        • 2017-10-02
        • 2018-06-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多