简体   繁体   中英

Writing a loop in R

I have written a loop in R. The code is expected to go through a list of variables defined in a list and then for each of the variables perform a function.

Problem 1 - I cannot loop through the list of variables
Problem 2 - I need to insert each output from the values into Mongo DB

Here is an example of the list:

121715771201463_626656620831011
121715771201463_1149346125105084

Based on this value - I am running a code and i want this output to be inserted into MongoDB. Right now only the first value and its corresponding output is inserted

test_list <- C("121715771201463_626656620831011","121715771201463_1149346125105084","121715771201463_1149346125105999")

for (i in test_list) { //myfunction// mongo.insert(mongo, DBNS, i) }

I am able to only pick the values for the first value and not all from the list

Any help is appreciated.

Try this example, which prints the final characters

myfunction <- function(x){ print( substr(x, 27, nchar(x)) ) } 

test_list <- c("121715771201463_626656620831011", 
               "121715771201463_1149346125105084", 
               "121715771201463_1149346125105999")
for (i in test_list){ myfunction(i) }
for (j in 1:length(test_list)){ myfunction(test_list[j]) } 

The final two lines should each produce

[1] "31011"
[1] "105084"
[1] "105999"

It is not clear whether "variable" is the same as "value" here.

If what you mean by variable is actually an element in the list you construct, then I think Ilyas comment above may solve the issue.

If "variable" is instead an object in the workspace, and elements in the list are the names of the objects you want to process, then you need to make sure that you use get . Like this:

for(i in ls()){
    cat(paste(mode(get(i)),"\n") )
}

ls() returns a list of names of objects. The loop above goes through them all, uses get on them to get the proper object. From there, you can do the processing you want to do (in the example above, I just printed the mode of the object).

Hope this helps somehow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM