subsetting data frame by row index

前端 未结 2 1565
-上瘾入骨i
-上瘾入骨i 2021-01-18 19:13

Why is my last step converting the data frame to a vector? I want to keep the first 6000 observations in the data frame key.

  set.seed(1)
  key         


        
2条回答
  •  囚心锁ツ
    2021-01-18 19:45

    It's being coerced to a vector basically because it can be and that's the default coercion when there's only 1 element. R is trying to be "helpful".

    This will keep it as a dataframe:

    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
    

提交回复
热议问题