首页 > 解决方案 > 通过为每列动态添加前缀来更新列值

问题描述

我有一个 for 循环,我在其中创建一个数据框。因为该数据框在每一轮中将采用不同的形状。同时我在每一轮中创建字符串向量,其中向量的长度等于数据的列数框架。作为随机轮次中的示例,数据框是merged_,字符串向量是out.names

merged_ <-  data.frame(V8 = c(19, 19, 1, 4, 4, 4),
                 V9 = c("9P0480", "9P0480", "9P0480", "9P0480", "9P0480", "9P0480"),
                 V10 = c(0,0,0,0,0,0),
                 V11 = c(4580,4580,4580,4580,4580,4580))

out.names <- c("hello","hello2","hello3","hello4")

现在我需要通过添加字符串值作为前缀来更新每一列。像这样输出

df_new <- data.frame(V8 = c("hello:19", "hello:19", "hello:1", "hello:4", "hello:4", "hello:4"),
V9 = c("hello2:9P0480", "hello2:9P0480", "hello2:9P0480", "hello2:9P0480", "hello2:9P0480", "hello2:9P0480"),
V10 = c("hello3:0","hello3:0","hello3:0","hello3:0","hello3:0","hello3:0"),
V11 = c("hello4:4580","hello4:4580","hello4:4580","hello4:4580","hello4:4580","hello4:4580"))

        V8            V9      V10         V11
1 hello:19 hello2:9P0480 hello3:0 hello4:4580
2 hello:19 hello2:9P0480 hello3:0 hello4:4580
3  hello:1 hello2:9P0480 hello3:0 hello4:4580
4  hello:4 hello2:9P0480 hello3:0 hello4:4580
5  hello:4 hello2:9P0480 hello3:0 hello4:4580
6  hello:4 hello2:9P0480 hello3:0 hello4:4580

到目前为止我尝试的是,尝试使用 for 循环更新每一列。

for (col in 1:ncol(merged_)) {

    merged_[,col] <- paste0(out.names[col],":",merged_[,col])
  }

这是我尝试上述代码时的错误

(merged_, , col) 中的错误[.data.table:j([...] 内的第二个参数)是单个符号,但未找到列名 'col'。也许您打算使用 DT[,..col] 或 DT[,col,with=FALSE]。与 data.frame 的这种差异是经过深思熟虑的,并在 FAQ 1.1 中进行了解释。

这可以通过使用一些矢量化方法来解决,而不使用 for 循环。

标签: rstringfor-loopconcatenation

解决方案


我们可以按列使用Mappaste值。out.namesmerged_

merged_[] <- Map(paste, out.names, merged_, sep = ":")
merged_

#        V8            V9      V10         V11
#1 hello:19 hello2:9P0480 hello3:0 hello4:4580
#2 hello:19 hello2:9P0480 hello3:0 hello4:4580
#3  hello:1 hello2:9P0480 hello3:0 hello4:4580
#4  hello:4 hello2:9P0480 hello3:0 hello4:4580
#5  hello:4 hello2:9P0480 hello3:0 hello4:4580
#6  hello:4 hello2:9P0480 hello3:0 hello4:4580

这类似于map2in purrr

merged_[] <- purrr::map2(out.names, merged_, paste, sep = ":")

推荐阅读