本文介绍了使用R将列名称插入其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在其值中插入列名",部门".我有这样的代码:

I need to insert Column Name, Department, into its value. i have code like here:

Department <- c("Store1","Store2","Store3","Store4","Store5")
Department2 <- c("IT1","IT2","IT3","IT4","IT5")
x <- c(100,200,300,400,500)
Result <- data.frame(Department,Department2,x)
Result

预期结果如下:

Department <- c("Department_Store1","Departmentz_Store2","Department_Store3","Department_Store4","Department_Store5")
Department2 <- c("Department2_IT1","Department2_IT2","Department2_IT3","Department2_IT4","Department2_IT5")
x <- c(100,200,300,400,500)
Expected.Result <- data.frame(Department,Department2,x)
Expected.Result

有人可以帮忙吗?谢谢

推荐答案

如果将相关的列名收集到向量 dep_col 中,则这是一个干净的 base R for循环的解决方案:

If you gather the column names in question into a vector dep_col, this is a clean base R solution with a for loop:

df <- data.frame(x = 1:5,
                 Department = paste0("Store", 1:5),
                 Department2 = paste0("IT", 1:5))

dep_col <- names(df)[-1]

for (c in dep_col)
  df[[c]] <- paste(c, df[[c]], sep = "_")

这篇关于使用R将列名称插入其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 03:14