-1

I have a data frame (df) with two columns named: Peter_Smith and Peter_Dow

df <- as_data_frame(matrix(ncol=2, nrow=2))
namesDF <- c("Peter_Smith", "Peter_Dow" )
names(df) <- namesDF

I want to get, for example, first column using:

library('dplyr')
target <- "Smith"
df1 <- select(df, eval(parse(text=paste0('Peter_', target)))

And get the next ERROR:

Error in eval(parse(text = paste0("Peter_", target))) : 
object 'Peter_Smith' not found

Why?

I use R version 3.5.3 (2019-03-11) -- "Great Truth"

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
MariaMaria1
  • 25
  • 1
  • 6

2 Answers2

1

Try select(df, !!paste0('Peter_', target))

Sonny
  • 3,083
  • 1
  • 11
  • 19
0
target <- "Smith"
target <- enquo(target)
df1 <- select(df, paste0('Peter_', !!target))

Hope it helps.

Pablo Rod
  • 669
  • 4
  • 10