如何从r [duplicate]中的data.frame中删除所有行

时间:2022-01-06 05:11:53

This question already has an answer here:

这个问题在这里已有答案:

I have a data frame from which I want to delete all rows while keeping original structure (columns).

我有一个数据框,我希望在保留原始结构(列)的同时删除所有行。

 ddf
  vint1 vint2 vfac1 vfac2
1     9    10     1     3
2     9     6     3     4
3     6     2     2     2
4    10     6     2     4
5     7    12     3     2
> 
> 
> 
> dput(ddf)
structure(list(vint1 = c(9L, 9L, 6L, 10L, 7L), vint2 = c(10L, 
6L, 2L, 6L, 12L), vfac1 = structure(c(1L, 3L, 2L, 2L, 3L), .Label = c("1", 
"2", "3"), class = "factor"), vfac2 = structure(c(2L, 3L, 1L, 
3L, 1L), .Label = c("2", "3", "4"), class = "factor")), .Names = c("vint1", 
"vint2", "vfac1", "vfac2"), class = "data.frame", row.names = c(NA, 
-5L))

I tried:

我试过了:

ddf = NA

for(i in 1:nrow(ddf) ddf[i,] = NULL

but they do not work. Thanks for your help on this basic question.

但他们不起作用。感谢您对这个基本问题的帮助。

1 个解决方案

#1


18  

If you really want to delete all rows:

如果你真的想删除所有行:

> ddf <- ddf[0,]
> ddf
[1] vint1 vint2 vfac1 vfac2
<0 rows> (or 0-length row.names)    

If you mean by keeping the structure using placeholders:

如果您的意思是使用占位符保持结构:

> ddf[,]=matrix(ncol=ncol(ddf), rep(NA, prod(dim(ddf))))
> ddf
  vint1 vint2 vfac1 vfac2
1    NA    NA    NA    NA
2    NA    NA    NA    NA
3    NA    NA    NA    NA
4    NA    NA    NA    NA
5    NA    NA    NA    NA 

#1


18  

If you really want to delete all rows:

如果你真的想删除所有行:

> ddf <- ddf[0,]
> ddf
[1] vint1 vint2 vfac1 vfac2
<0 rows> (or 0-length row.names)    

If you mean by keeping the structure using placeholders:

如果您的意思是使用占位符保持结构:

> ddf[,]=matrix(ncol=ncol(ddf), rep(NA, prod(dim(ddf))))
> ddf
  vint1 vint2 vfac1 vfac2
1    NA    NA    NA    NA
2    NA    NA    NA    NA
3    NA    NA    NA    NA
4    NA    NA    NA    NA
5    NA    NA    NA    NA