0

I am trying to automatically get, in a loop, a column from a dataframe. It is important to get this column by '$' operator df$column, because if I slice the df like this df[,c('column')] then I don't get anymore a haven_labelled object.

Example df:

colName  colName2
a         1
b         2
c         3
d         4

I was trying get(paste0('df$', colName)), but I am getting:

Error in get(paste0('df$', colName)) : object 'df$colName' not found

However, if I write: df$colName in my console, the column is printed. So the problem is that get only identifies the df as an object, but not its columns. Do you know how can I solve this?

What I would like is to get the following vector: c('a','b','c','d'), but it must keep its labels.

Thanks!

Jenifer
  • 37
  • 4
  • You can retrieve columns from a df with `df[[colName]]`. Anyhow, why not `lapply` or `Map` across the dataframe (which is a *list*, albeit a rectangular one), or `dplyr::across` if you prefer tidyverse packages? – I_O May 30 '23 at 08:31
  • 1
    This seems like a bit of an xy problem. It doesn't have anything to do with the `$` operator. If I put a haven labelled column in a data frame, then `df$colName`, `df[['colName']]` and `df[, c('colName')]` all return a haven labelled vector. Can you provide a reproducible example that replicates your problem? – Allan Cameron May 30 '23 at 08:31
  • 1
    Maybe you can use: `eval(parse(text = paste0('df$', colName)))` ? – GKi May 30 '23 at 08:45
  • Using `eval(parse(...))` is generally discouraged, see this question for details: https://stackoverflow.com/questions/13649979/what-specifically-are-the-dangers-of-evalparse – f.lechleitner May 30 '23 at 09:57

0 Answers0