如何在 R 中的列的开头插入“1”?

How to insert "1 " in the start for a column in R?

我的数据 (master_data) 中有一列名为单位。

master_data$unit <- c("Tonnes","1000 Tonnes","Numbers","1000 Numbers")

我想转换此列以便我得到这个

master_data$unit <- c("1 Tonnes","1000 Tonnes","1 Numbers", "1000 Numbers")

我想这样做是为了将单位分成两列,1/1000s 和 Tonnes/Numbers

我试图找到单位的长度然后使用粘贴命令,但它不起作用

master_data$unit_len <- sapply(strsplit(master_data$unit, " "), length)


if (master_data$unit_len == 1) {
  paste("1 ", master_data$unit, sep="")
}

然而,这不起作用。

检查 unit 是否以数字开头。如果没有,paste1开头

unit <- c("Tonnes","1000 Tonnes","Numbers","1000 Numbers")
ifelse(grepl("^\d", unit), unit, paste("1", unit))
#[1] "1 Tonnes"     "1000 Tonnes"  "1 Numbers"    "1000 Numbers"

我们可以使用sub。这匹配一个字符串,其中所有字符都是 "word characters" 并替换为“1(匹配的字符)”:

unit <- c("Tonnes","1000 Tonnes","Numbers","1000 Numbers")

sub('^(\w+)$', '1 \1', unit)
# [1] "1 Tonnes"     "1000 Tonnes"  "1 Numbers"    "1000 Numbers"