Insert Column Name into its Value using R

好久不见. 提交于 2021-02-08 08:52:05

问题


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

The expected result is like:

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

Can somebody help? Thanks


回答1:


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 = "_")



回答2:


Another way with dplyr and tidyr:

library(dplyr)
library(tidyr)

# Convert to character to avoid warning message, will convert all columns to character
Result[] <- lapply(Result, as.character)

Result %>%
  mutate_if(is.factor, as.character) %>% # optional, only convert factor to character, retain all other types
  gather(key, value, -x) %>% 
  mutate(var = paste(key, value, sep = "_")) %>% 
  select(-value) %>% 
  spread(key,var)

    x        Department     Department2
1 100 Department_Store1 Department2_IT1
2 200 Department_Store2 Department2_IT2
3 300 Department_Store3 Department2_IT3
4 400 Department_Store4 Department2_IT4
5 500 Department_Store5 Department2_IT5

Data:

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



回答3:


If I understand correctly, the OP wants to prepend the values in all columns starting with "Department" by the respective column name.

Edit By request of the OP, the code to select columns has been generalized to pick additional column names.

Here is a solution using data.table's fast set() function:

library(data.table)
setDT(Result)
cols <- stringr::str_subset(names(Result), "^(Department|Division|Team)")
for (j in cols) {
  set(Result, NULL, j, paste(j, Result[[j]], sep = "_"))
}
Result
          Department     Department2   x
1: Department_Store1 Department2_IT1 100
2: Department_Store2 Department2_IT2 200
3: Department_Store3 Department2_IT3 300
4: Department_Store4 Department2_IT4 400
5: Department_Store5 Department2_IT5 500

Note that set() updates by reference, i.e., without copying the whole object.



来源:https://stackoverflow.com/questions/49173202/insert-column-name-into-its-value-using-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!