William Bernard - 1 year ago 84
R Question

# Nested Loop in r

I am having trouble writing an algo in r, in python this wouldnt be a big deal but r's syntax has thrown me off.
I would like to set the first index of z and nums equal to eachother and put it into a list.
Once in a list I would like to print the letter of a negative number.
Then i would like to print the numbers that correspond to j k l.

``````nums<-c(1.0, 3.0, -2, 8, -4, 4, 2, -3, 9, 1, 4, 2, 2, 1, 8, 2)
z<-c("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p")
lets<-c(j,k,l)
for (i in nums){
for(j in z) {
}}
list=((a,1),(b,3),(c,-2),(d,8),(e,-4),(f,4),(g,2),(h,-3),(i,9),(j,1),(k,4),(l,2),(m,2),(n,1),(o,8),(p,2))

negative=c,e,h,
letters=1,4,2
``````

What you could do is (using your data):

``````df <- data.frame(z,nums, stringsAsFactors = FALSE)
``````

There all the letters and nums in

``````    > df
z nums
1  a    1
2  b    3
3  c   -2
4  d    8
5  e   -4
6  f    4
7  g    2
8  h   -3
9  i    9
10 j    1
11 k    4
12 l    2
13 m    2
14 n    1
15 o    8
16 p    2
``````

And then you can access what ever you want:

``````df\$z[df\$nums<0]
``````

Results in:

``````[1] "c" "e" "h"
``````

And to get the number for j,k,l you can use grepl:

``````df[grepl("[j,k,l]", df\$z),]
z nums
10 j    1
11 k    4
12 l    2
``````

Then you have again a sub data frame or for just the numbers do:

``````df\$nums[grepl("[j,k,l]", df\$z)]
[1] 1 4 2
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download