[Rd] cannot delete the last column of a dataframe using "[<-" (PR#9565)

hsiu-khuern.tang at hp.com hsiu-khuern.tang at hp.com
Wed Mar 14 18:58:31 CET 2007


Hi,

If df is a dataframe, its last column can't be deleted using "[<-", but
other columns can be deleted this way.

Example:

> (df <- df0 <- data.frame(x = 1:3, y = 4:6, z = 7:9))
  x y z
1 1 4 7
2 2 5 8
3 3 6 9
> df[, "z"] <- NULL
Error in x[[jj]] : subscript out of bounds
> df[, 3] <- NULL
Error in x[[jj]] : subscript out of bounds
> df["z"] <- NULL
Error in x[[jj]] : subscript out of bounds
> df[3] <- NULL
Error in x[[jj]] : subscript out of bounds

> df[, "y"] <- NULL
> df
  x z
1 1 7
2 2 8
3 3 9
> df <- df0; df[, 2] <- NULL
> df <- df0; df["y"] <- NULL
> df <- df0; df[2] <- NULL

Deleting using "$<-" and "[[<-" works for all columns.  Is it wrong to use
"[<-" for deleting?  help("[<-.data.frame") has an example, but it doesn't work
for deleting the last column either:

> sw <- swiss[1:5, 1:4]  # select a manageable subset

> ## adding a column
> sw["new1"] <- LETTERS[1:5]   # adds a character column
> sw[["new2"]] <- letters[1:5] # ditto
> sw[, "new3"] <- LETTERS[1:5] # ditto
> sw$new4 <- 1:5
> sw$new4 <- NULL              # delete the column
> (sw0 <- sw)
             Fertility Agriculture Examination Education new1 new2 new3
Courtelary        80.2        17.0          15        12    A    a    A
Delemont          83.1        45.1           6         9    B    b    B
Franches-Mnt      92.5        39.7           5         5    C    c    C
Moutier           85.8        36.5          12         7    D    d    D
Neuveville        76.9        43.5          17        15    E    e    E

> # This works:
> sw[6:8] <- list(letters[10:14], NULL, aa=1:5) # delete col7, update 6, append

> # But this doesn't:
> sw <- sw0
> sw[6:8] <- list(letters[10:14], aa=1:5, NULL)
Error in x[[jj]] : subscript out of bounds

Best,
Hsiu-Khuern.

----------
Version:
 platform = i486-pc-linux-gnu
 arch = i486
 os = linux-gnu
 system = i486, linux-gnu
 status = 
 major = 2
 minor = 4.1
 year = 2006
 month = 12
 day = 18
 svn rev = 40228
 language = R
 version.string = R version 2.4.1 (2006-12-18)

Locale:
C

Search Path:
 .GlobalEnv, package:datasets, package:stats, package:graphics, package:grDevices, package:utils, package:methods, Autoloads, package:base



More information about the R-devel mailing list