Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

Hi I would like to run a loop from a list and have it go through a function one at a time using R?

I have a dataframe(df) that looks like this

  a|    b|    c|    d|    e|    f
val1 val2 val3  val4   val5  val6

my list is

 list<-c("b","c","d")

I want it so that only b,c, and d run through a function trimws. However it can be anything.

for (i in list) {
  assign(df, get(df) %>% trimws (i), envir = .GlobalEnv)}

I tried running this loop but it did not work. I received an error message

Error: unexpected '}' in "  assign(df, get(df) %>% trimws (i), envir = .GlobalEnv)}"

At the end of the day i want to run a function specifically in the three columns only and for it to ignore the ones not in the list

question from:https://stackoverflow.com/questions/66064090/hi-i-would-like-to-run-a-loop-from-a-list-and-have-it-go-through-a-function-one

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This should help you complete a working loop to build from. This should help you with skipping certain values.

    list <- c("b","c","d")

    Output <- NULL

    for(i in list){
        if(i == "c"){next}
        
        Output <- c(Output, i)
    }
Output
[1] "b" "d"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...