Remove quotation marks from a vector element to use it as a value

Suppose I have a vector xwhose elements I want to use to extract columns from a matrix or data frame M.

If x[1] = "A", I cannot use a M$x[1]column with a heading to extract A, because it is M$Arecognized, but M$"A"not. How to remove the quotation marks that M$x[1]was M$A, not M$"A"in this case?

+1
source share
1 answer

Do not use $in this case; use instead [. Here is a minimal example (if I understand what you are trying to do).

mydf <- data.frame(A = 1:2, B = 3:4)
mydf
#   A B
# 1 1 3
# 2 2 4

x <- c("A", "B")
x
# [1] "A" "B"

mydf[, x[1]]                  ## As a vector
# [1] 1 2

mydf[, x[1], drop = FALSE]    ## As a single column `data.frame`
#   A
# 1 1
# 2 2

, R Inferno. 8: ", , ", " ".... The main difference is that $ does not allow computed indices, whereas [[ does. ?Extract.


, - , , , [row, column] ( $ matrix).

+1

All Articles