gpt4 book ai didi

r - 按行索引子集数据帧

转载 作者:行者123 更新时间:2023-12-04 21:15:17 24 4
gpt4 key购买 nike

为什么我的最后一步是将数据框转换为向量?我想保留数据框中的前 6000 个观察值 key .

  set.seed(1)
key <- data.frame(matrix(NA, nrow = 10000, ncol = 1))
names(key) <- "ID"
key$ID <- replicate(10000,
rawToChar(as.raw(sample(c(48:57,65:90,97:122), 8, replace=T))))
key <- unique(key) # still a data frame
key <- key[1:6000,] # no longer a data frame

最佳答案

 key1 <- key[1:6000,,drop=F] #should prevent the data.frame from converting to a vector.

根据 ?Extract.data.frame 的文档

drop: logical. If ‘TRUE’ the result is coerced to the lowest possible dimension. The default is to drop if only one column is left, but not to drop if only one row is left.



或者,您可以使用 subset ,但通常情况下,这会慢一些。这里的 row.names 是来自 1 的数字至 10000
 key2 <- subset(key, as.numeric(rownames(key)) <6000)

is.data.frame(key2)
#[1] TRUE

因为,
 ## S3 method for class 'data.frame'
subset(x, subset, select, drop = FALSE, ...) #by default it uses drop=F

关于r - 按行索引子集数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25165996/

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