Michael
Michael

Reputation: 575

Paste a number as macro

Consider the following dataset:

d <- data.frame(replicate(2,sample(0:1,10,rep=TRUE)))
colnames(d) <- c("2000","2001")

I want to make the following subset:

d2 <- data.frame(d$`2000`)

However, instead of using $2000, I want to create a macro which I can use instead. For instance,

year <- 2000

How do I use this new value as a macro. I have tried with:

d2 <- data.frame(d$`formula(paste(year))`)

But this does not work. Can anyone help me?

Upvotes: 0

Views: 47

Answers (4)

GKi
GKi

Reputation: 39657

You can use match and colnames to select the column.

d[match(year, colnames(d))]
#   2000
#1     1
#2     1
#3     1
#4     1
#5     0
#6     0
#7     0
#8     0
#9     1
#10    0

or which.

d[which(year == colnames(d))]

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101209

You can use toString or class (similar to the solution as.character() by @Ronak Shah), i.e.,

d2 <- d[toString(year)]

or

d2 <- d[`class<-`(year,"character")]

Both of them will get

> d2
   2000
1     1
2     1
3     0
4     1
5     1
6     1
7     0
8     1
9     0
10    1

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388862

You could change the year value to character and then select the column.

d[as.character(year)]

#   2000
#1     1
#2     1
#3     1
#4     0
#5     1
#6     0
#7     1
#8     1
#9     1
#10    0

Or similarly with dplyr::select

dplyr::select(d, as.character(year))

Upvotes: 3

Jeroen Colin
Jeroen Colin

Reputation: 345

Usign dplyr you can do:

d %>% select(paste0(year))

Upvotes: 0

Related Questions