在子集化之后将单个圆柱形数据帧转换为向量的原因

Prr*_*dep 1 r subset dataframe

我有一个圆柱数据框架结构.基于条件,我在运行时期间对数据帧进行了子集化.我观察到数据帧在子集化后被转换为向量.我已经使用该as.data.frame()函数实现了数据帧结构.

# random generation of the values    
df <- data.frame(a=sample(1:1000,100))
#checking the class of the object
class(df)
#dimensions
dim(df)
#[1] 100   1
#subsetting the data with a random value present in the df, here 547
df_sub <- df[-df$a==547,]
# checking the subset dataset class
class(df_sub)
#[1] "integer"
Run Code Online (Sandbox Code Playgroud)

我想知道如何在不明确使用该as.data.frame()函数的情况下保留数据框架结构.

lmo*_*lmo 6

R经常在子集化后尝试简化对象.如果不需要,可以使用drop = FALSE参数来防止这种简化:

df_sub <- df[-df$a==547,, drop=FALSE]

> class(df_sub)
[1] "data.frame"
Run Code Online (Sandbox Code Playgroud)

drop = FALSE也可用于矩阵:

myMat <- matrix(1:10, 5)

> class(myMat[, 1])
[1] "integer"
> 
> class(myMat[, 1, drop=FALSE])
[1] "matrix"
> 
> class(myMat[1, ])
[1] "integer"
> 
> class(myMat[1, , drop=FALSE])
[1] "matrix"
Run Code Online (Sandbox Code Playgroud)