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,
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,
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.
Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Your vector has columns? Unless I'm terribly mistaken, wouldn't that make it a dataframe?
I am sorry, I mean it is a dataframe, but it is atomic..
Can't you just:
what is the structure?
That's a matrix, not a data frame.