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

Luigi Marongiu m@rong|u@|u|g| @end|ng |rom gm@||@com
Mon Aug 9 13:16:02 CEST 2021


Thank you but I think I got it wrong:
```
> df = data.frame(VAR = letters[1:5], VAL = c(1, 2, NA, 2, NA)); df
  VAR VAL
1   a   1
2   b   2
3   c  NA
4   d   2
5   e  NA
> vect = letters[1:5]
> df[df[['vect[2]']] == 2, 'vect[2]'] <- "No"; df
  VAR VAL vect[2]
1   a   1    <NA>
2   b   2    <NA>
3   c  NA    <NA>
4   d   2    <NA>
5   e  NA    <NA>
```

On Mon, Aug 9, 2021 at 11:25 AM Ivan Krylov <krylov.r00t using gmail.com> wrote:
>
> 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,
> Ivan



-- 
Best regards,
Luigi



More information about the R-help mailing list