Luigi Marongiu
2021-Aug-09 08:26 UTC
[R] substitute column data frame based on name stored in variable in r
Hello, I would like to recursively select the columns of a dataframe by strong the names of the dataframe in a vector and extracting one element of the vector at a time. This I can do with, for instance: ``` vect = names(df) sub_df[vect[1]] ``` The problem is that I would like also to change the values of the selected column using some logic as in `df$column[df$column == value] <- new.value`, but I am confused on the syntax for the vectorized version. Specifically, this does not work: ``` sub_df[vect[1] == 0] = "No" ``` What would be the correct approach? Thank you
Jim Lemon
2021-Aug-09 08:53 UTC
[R] substitute column data frame based on name stored in variable in r
Hi Luigi, It looks to me as though you will have to copy the data frame or store the output in a new data frame. Jim On Mon, Aug 9, 2021 at 6:26 PM Luigi Marongiu <marongiu.luigi at gmail.com> wrote:> > Hello, > I would like to recursively select the columns of a dataframe by > strong the names of the dataframe in a vector and extracting one > element of the vector at a time. This I can do with, for instance: > ``` > vect = names(df) > sub_df[vect[1]] > ``` > > The problem is that I would like also to change the values of the > selected column using some logic as in `df$column[df$column == value] > <- new.value`, but I am confused on the syntax for the vectorized > version. Specifically, this does not work: > ``` > sub_df[vect[1] == 0] = "No" > ``` > What would be the correct approach? > Thank you > > ______________________________________________ > R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.
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