Subset of row data

Why is my last step converting a data frame to a vector? I want to save the first 6,000 observations in a data frame 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
+4
source share
2 answers
 key1 <- key[1:6000,,drop=F] #should prevent the data.frame from converting to a vector.

According to the documentation ?Extract.data.frame

fall: logical. If "TRUE" the result is forced to the lowest possible size. The default value is crash if only one Column is left, but is not discarded if only one row remains.

Or you can use subset, but usually it is a bit slower. Here row.names are numbers from 1to10000

 key2 <- subset(key, as.numeric(rownames(key)) <6000)

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

because

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

, . R "" .

:

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)  
key <- as.data.frame(key[1:6000,]) # still a data frame
0

All Articles