[R] substitute column data frame based on name stored in variable in r

Ivan Krylov kry|ov@r00t @end|ng |rom gm@||@com
Mon Aug 9 11:24:51 CEST 2021

On Mon, 9 Aug 2021 10:26:03 +0200
Luigi Marongiu <marongiu.luigi using gmail.com> wrote:

> vect = names(df)
> sub_df[vect[1]]

> df$column[df$column == value] <- new.value

Let's see, an equivalent expression without the $ syntax is
`df[['column']][df[['column']] == value] <- new.value`. Slightly
shorter, matrix-like syntax would give us
`df[df[['column']] == value, 'column'] <- new.value`.

Now replace 'column' with vect[i] and you're done. The `[[`-indexing is
used here to get the column contents instead of a single-column
data.frame that `[`-indexing returns for lists.

Also note that df[[names(df)[i]]] should be the same as df[[i]] for
most data.frames.

Best regards,

More information about the R-help mailing list