Ivan Krylov
2021-Aug-09 09:24 UTC
[R] substitute column data frame based on name stored in variable in r
On Mon, 9 Aug 2021 10:26:03 +0200 Luigi Marongiu <marongiu.luigi at gmail.com> wrote:> vect = names(df) > sub_df[vect[1]]> df$column[df$column == value] <- new.valueLet'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
Luigi Marongiu
2021-Aug-09 11:16 UTC
[R] substitute column data frame based on name stored in variable in r
Thank you but I think I got it wrong: ```> df = data.frame(VAR = letters[1:5], VAL = c(1, 2, NA, 2, NA)); dfVAR 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"; dfVAR 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 at gmail.com> wrote:> > On Mon, 9 Aug 2021 10:26:03 +0200 > Luigi Marongiu <marongiu.luigi at 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