[R] add specific fields in for loop

@vi@e@gross m@iii@g oii gm@ii@com @vi@e@gross m@iii@g oii gm@ii@com
Tue Nov 15 18:22:22 CET 2022


As Bert pointed out, it may not be clear what you want.

As a GUESS, you have some arbitrary data.frame object with multiple columns and you want to do something on selected columns. Consider changing your idea to be in several stages for simplicity and then optionally later rewriting it.

So step 1 is to get a vector of column names. The normal way to do this in base R is not with a function called columns(df) but colnames(df) ...

Step 2 is to use one of many techniques that take that vector of names and select the ones you want to keep. In base R there are many ways to do that including using regular expressions as in the "grep" family of functions. You may end up with a new vector of names perhaps shorter or in a different order.

Step 3 is to use those names in your loop. If you want say to convert a column from character to numeric, and your loop index is "current" you might write something like:
	df[current] <- as.numeric(df[current])

There are many ways and it depends on what exactly you want to do. There are packages designed to make some of these things fairly simple, such as dplyr where you can ask to match names that start or end a certain way or that are of certain types.


-----Original Message-----
From: R-help <r-help-bounces using r-project.org> On Behalf Of Kai Yang via R-help
Sent: Tuesday, November 15, 2022 11:18 AM
To: R-help Mailing List <r-help using r-project.org>
Subject: [R] add specific fields in for loop

Hi Team,
I can write a for loop like this:
for (i in columns(df)){

But it will working on all column in dataframe df. If I want to work on some of specific fields (say: the fields' name content 'date'), how should I modify the for loop? I changed the code below, but it doesn't work.
for (i in columns(df) %in% 'date' ){

Thank you,

	[[alternative HTML version deleted]]

R-help using 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.

More information about the R-help mailing list