gpt4 book ai didi

r - cbind 放置 1 而不是字符

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

我要把 R 扔出窗外。 R 很可爱,但有时一个小问题需要几个小时才能解决。

得到这个 df:

Product <- c("Basket", "Basket", "Basket", "Apple", "Apple", "Apple", "Corn", "Corn", "Corn", "Basket")
Place <- c("America", "Europe", "Africa", "America", "Europe", "Africa", "America", "Europe", "Africa", "America")
Detail <- c("Income", "Income", "Outcome", "Outcome", "Income", "Outcome", "Outcome", "Income", "Income", "Outcome")
Valuex <- c(1500, 2000, 2000, 4000, 5000, 700, 4000, 2000, 7000, 450)
df_test <- data.frame(Product, Place, Detail, Valuex, stringsAsFactors = FALSE)

然后,我通过这样做创建另一个 data.frame:

test <- df_test[1,]

最后,我像这样使用 cbind:

test[1,1:4] <- cbind(df_test[1,1:2], "Prueba", df_test[1, 4])

当我查看数据框 test 时,我发现:

  Product   Place Detail Valuex
1 Basket America 1 1500

不是保存“Prueba”,而是保存 1。

我试过 as.character("Prueba"), c("Prueba"), paste("Prueba") , 但它仍然是 1。

谁能帮帮我?

最佳答案

您一直看到 1 而不是 Preuba 的原因是该值正在转换为一个因子,并且您看到的是水平值。您可以通过将 test 的第一行分配给 cbind 调用来避免这种情况,该调用将 stringsAsFactors 设置为 false,例如

test <- df_test[1,]
df <- cbind(df_test[1,1:2], "Prueba", df_test[1, 4], stringsAsFactors=FALSE)
test[1,] <- df
test

Product Place Detail Valuex
1 Basket America Prueba 1500

Demo

但是,一个可能更好的解决方法是将向量分配给 test 数据框的第一行:

test[1,] <- c(df_test[1,1:2], "Prueba", df_test[1, 4])

关于r - cbind 放置 1 而不是字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48970974/

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