简体   繁体   中英

Reordering column in R dataframe

This code:

df <- structure(c(0.162568559415789, 0.21553449994005, 0.189530046160695, 
0.136847489883353, 0.178477010023321, 0, 0.168176796512036, 0.330921388911015, 
0.347470738098292, 0.168868189119251, 0.161459232469667, 0.540106475382717, 
0.487429698101744, 0.374124445062667, 0.319174414140653, 0.467838144637299, 
0.497981004663612, 0.283910424346759, 0.181824945970431, 0.0794196660862671, 
0.14382480160036, 0.226446176360097, 0.1620827528434, 0.175983100270524
), .Dim = c(6L, 4L), .Dimnames = list(c("lincR-Agpat9-3AS8Kk-3ASK3K", 
"lincR-Asap1-3SS3Rik-5S-13K", "lincR-Lbh-3-4K470KKKSK-13K", "lincR-Mapk9-3S2096K-3S", 
"lincR-Tbl1xr1-5-0K4K6KS13K", "lincR-Zfand2a-5SSik-3S3K3K"), 
    c("naive", "a", "b", "c")))

Produces this:

> df
                               naive         a         b          c
lincR-Agpat9-3AS8Kk-3ASK3K 0.1625686 0.1681768 0.4874297 0.18182495
lincR-Asap1-3SS3Rik-5S-13K 0.2155345 0.3309214 0.3741244 0.07941967
lincR-Lbh-3-4K470KKKSK-13K 0.1895300 0.3474707 0.3191744 0.14382480
lincR-Mapk9-3S2096K-3S     0.1368475 0.1688682 0.4678381 0.22644618
lincR-Tbl1xr1-5-0K4K6KS13K 0.1784770 0.1614592 0.4979810 0.16208275
lincR-Zfand2a-5SSik-3S3K3K 0.0000000 0.5401065 0.2839104 0.17598310

What I want to do then is to reorder that data frame the following way. But why it failed?

> df[c("naive","b","c","a")]
[1] NA NA NA

That's a matrix, not a data frame. Use a comma

df[, c("naive", "b", "c", "a")]

An easy way to tell the difference from the dput() output is (1) the absence of the class attribute (which would say "data.frame" for a data frame), and (2) the inclusion of .Dimnames (in a data frame it would say .Names for column names and row.names for row names).

Of course, the best way is to just check

class(df)
# [1] "matrix"

For matrix subsetting, you need to use a comma to access by column. In a data frame, you don't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM