我在 H2O 中有一个数据框(称为 df1.hex),我正在尝试使用 h2o.cbind 向该数据框添加新列。我正在使用 h2o 3.18.0.4。
我在下面显示的代码只是我正在尝试做的简化版本。实际上,我正在根据各种条件向 df1.hex 数据框添加新列。最重要的是,每当我需要将新列附加到 df1.hex 时,我都希望能够使用“h2o.cbind”。所以,我必须在我的程序中多次调用 h2o.cbind 。我操作的真实数据集太大,我无法在 R 中完成所有这些操作,然后将其导出到 h2o 中。
考虑下面的代码:
# Let's load H2O and start up an H2O cluster
library(h2o)
h2o.init()
# Initialize a data frame with a column 'y'
df1 = data.frame(y=c('A', 'B', 'C'))
df1.hex = as.h2o(df1)
print(df1.hex)
# Need to append additional columns to df1.hex named x1, x2 etc...
for (i in 1:2) {
df2 = data.frame(x=c(1*i, 2*i, 3*i))
colnames(df2) = c(paste("x", i, sep='')) # x1, x2 etc...
df2.hex = as.h2o(df2)
print(paste("Iteration: ", i, ": Adding df2.hex...", sep=''))
print(df2.hex)
df1.hex = h2o.cbind(df1.hex, df2.hex) # Append x(i) to df1.hex data frame
}
print("The final dataset df1.hex: ")
print(df1.hex)
h2o.shutdown(prompt=FALSE)
输出如下:
> print(df1.hex)
y
1 A
2 B
3 C
[1] "Iteration: 1: Adding df2.hex..."
x1
1 1
2 2
3 3
[1] "Iteration: 2: Adding df2.hex..."
x2
1 2
2 4
3 6
[3 rows x 1 column]
[1] "The final dataset df1.hex: "
> print(df1.hex)
y x2 x20
1 A 2 2
2 B 4 4
3 C 6 6
尽管我添加了两个名为 x1 和 x2 的新列,但 df1.hex 的最终版本包含两个名为 x2 和 x20 的列。为什么会这样?
此外,x1 列完全消失了。我只看到 x2 列出现了两次。
如何修复我的代码以命名我的列 x1 和 x2 并按照我最初的意图在这些列中具有正确的值?
谢谢。
卡提克。
最佳答案
可能是 cbind
基本上只绑定(bind)最后一个运行元素,导致两个“x2”列,并且通过使其唯一,列名可以更改为“x20”。一种方法是将其分配给 list
然后 cbind
.
#initialize a `list` of length 2
lst <- vector("list", 2)
for (i in 1:2) {
#create the h2o dataset and assign it to each list element
lst[[i]] <- as.h2o(data.frame(x=c(1*i, 2*i, 3*i)))
#change the column names of the h2o dataset
names(lst[[i]]) <- paste0("x", i)
}
#do the cbind outside the loop
do.call(h2o.cbind, c(df1.hex, lst))
# y x1 x2
#1 A 1 2
#2 B 2 4
#3 C 3 6
#[3 rows x 3 columns]
或者这可以通过
%>%
在管道 ( tidyverse
) 中完成功能library(tidyverse)
map(1:2, ~ tibble(x = (1:3) * .x) %>%
set_names(., paste0("x", .x)) %>%
as.h2o) %>%
append(df1.hex, .) %>%
do.call(h2o.cbind, .)
# y x1 x2
#1 A 1 2
#2 B 2 4
#3 C 3 6
#[3 rows x 3 columns]
关于r - 使用 h2o.cbind 向 h2o 数据集添加列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49414212/