gpt4 book ai didi

r - 使用 R 将列名插入其值

转载 作者:行者123 更新时间:2023-12-05 02:16:38 24 4
gpt4 key购买 nike

我需要将列名、部门插入到它的值中。我有这样的代码:

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

有人可以帮忙吗?谢谢

最佳答案

dplyrtidyr 的另一种方式:

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

数据:

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

关于r - 使用 R 将列名插入其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49173202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com