how to get values from a columns from atomic vector without get the names of rows?
1
0
Entering edit mode
8.1 years ago
bxia ▴ 180

I have an atomic vector, so I can't use myVector$colname, when I use

myVector[, colname], it generates a huge vector, with rowname, value, rowname value.

Is there a easy way to do it?

Thanks,

R • 17k views
ADD COMMENT
1
Entering edit mode

Your vector has columns? Unless I'm terribly mistaken, wouldn't that make it a dataframe?

ADD REPLY
0
Entering edit mode

I am sorry, I mean it is a dataframe, but it is atomic..

ADD REPLY
1
Entering edit mode

Can't you just:

foo = myMatrix[,colname]
names(foo) = c()
ADD REPLY
0
Entering edit mode

what is the structure?

ADD REPLY
0
Entering edit mode
num [1:24488, 1:3] 17.62 4.03 7.36 8.87 10.2 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:24488] "(+)E1A_r60_1" "(+)E1A_r60_a107" "(+)E1A_r60_a135" "(+)E1A_r60_a20" ...
  ..$ : chr [1:3] "control1" "control2" "sample1"
ADD REPLY
0
Entering edit mode

That's a matrix, not a data frame.

ADD REPLY
0
Entering edit mode
8.1 years ago
ddiez ★ 2.0k

Devon's method works (never seen it before!). Also you can do:

# example data (convert data.frame to matrix).
tmp <- data.matrix(mtcars)[1:3, 1:3]
tmp
               mpg cyl disp
Mazda RX4     21.0   6  160
Mazda RX4 Wag 21.0   6  160
Datsun 710    22.8   4  108

# what we get:
tmp[, "mpg"]
    Mazda RX4 Mazda RX4 Wag    Datsun 710 
         21.0          21.0          22.8 

# what we want:
unname(tmp[, "mpg"])
[1] 21.0 21.0 22.8

# other options:
tmp2 <- tmp[, "mpg"]
names(tmp2) <- NULL # my choice.
names(tmp2) <- c() # Devon's choice.

All this happens because you are using a matrix (as noted in the comments). If you use a data.frame all this hassle goes away. The previous example without converting to matrix:

# get small data.
tmp  <- mtcars[1:3, 1:3]
tmp
               mpg cyl disp
Mazda RX4     21.0   6  160
Mazda RX4 Wag 21.0   6  160
Datsun 710    22.8   4  108

# all these give the same:
tmp[["mpg"]]
tmp[, "mpg"]
tmp$mpg
[1] 21.0 21.0 22.8

# to retain the names:
tmp[, "mpg", drop = FALSE]
               mpg
Mazda RX4     21.0
Mazda RX4 Wag 21.0
Datsun 710    22.8

I can't tell you whether your data is more suitable for matrix or data.frame- you have to decide yourself. Bear in mind that in a matrix all elements are of the same type (i.e. integer, numeric, character or logical), whereas in a data.frame, different columns can contain different types of data.

ADD COMMENT

Login before adding your answer.

Traffic: 2192 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6