gpt4 book ai didi

r - 从简单表中添加多列

转载 作者:行者123 更新时间:2023-12-05 01:52:19 25 4
gpt4 key购买 nike

我有两个数据表如下:

> have1
Column1 Column2 Column3
1: 100 200 159
2: 169 506 101
3: 100 200 636
---
123571 456 559 249
123572 654 883 423

> have2
variable value
1: Apple 0.25
2: Orange 2.68
3: Pear 0.11
---
10: Grape 5.27

我想做的是将 'have2' 中的 variable 作为列和 value 作为常量添加到 'have1',所以 'want' 是:

> want
Column1 Column2 Column3 Apple Orange Pear.... Grape
1: 100 200 159 0.25 2.68 0.11 5.27
2: 169 506 101 0.25 2.68 0.11 5.27
3: 100 200 636 0.25 2.68 0.11 5.27
---
123571 456 559 249 0.25 2.68 0.11 5.27
123572 654 883 423 0.25 2.68 0.11 5.27


我希望不使用 dplyr 并坚持使用 base R 或 data.table。这种合并需要适用于不同的 'have1' & 'have2''want' 集,因此尽量避免手动列出 中的所有变量>cbind(即 cbind(have1, Apple=0.25 etc...)...)

任何帮助,建议将不胜感激,谢谢!!

最佳答案

library(data.table)

cbind(have1, transpose(have2, make.names = "variable"))

输出

   Column1 Column2 Column3 Apple Orange Pear
1: 100 200 159 0.25 2.68 0.11
2: 169 506 101 0.25 2.68 0.11
3: 100 200 636 0.25 2.68 0.11

数据

have1 <- structure(list(Column1 = c(100L, 169L, 100L), Column2 = c(200L, 
506L, 200L), Column3 = c(159L, 101L, 636L)), class = c("data.table",
"data.frame"), row.names = c(NA, -3L))
setDT(have1)

have2 <- structure(list(variable = c("Apple", "Orange", "Pear"), value = c(0.25,
2.68, 0.11)), class = c("data.table", "data.frame"), row.names = c(NA,
-3L))
setDT(have2)

关于r - 从简单表中添加多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71642575/

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