2

I'm having a dataframe as like below. I need to extract df based on the region which is availabe in RL

    >avg_data
    region  SN      value
    beta    1       32
    alpha   2       44
    beta    3       55
    beta    4       60
    atp     5       22


    > RL
           V1
    1 beta
    2 alpha

That dataframe should be in array something like REGR[beta] which should contain beta related information as like below

    region  SN      value
    beta    1       32
    beta    3       55
    beta    4       60

Similarly for REGR[alpha]

    region  SN      value
    alpha   2       44

So that I can pass REGR as a argument for plotting graph.

    REGR <- data.frame()

    for (i in levels(RL$V1)){
     REGR[i,] <- avg_data[avg_data$region==i, ];
    }

I did some mistake in the above code. Please correct me.. Thank you

1 Answer 1

1

The split function may be of interest to you. From the help page, split divides the data in the vector x into the groups defined by f.

So for your data, it may look something like:

> split(avg_data, avg_data$region)
$alpha
  region SN value
2  alpha  2    44

$atp
  region SN value
5    atp  5    22

$beta
  region SN value
1   beta  1    32
3   beta  3    55
4   beta  4    60

If you want to filter out the records that do not occur in RL, I'd probably do that in a preprocessing step using the %in% function and [ for extraction:

x <- avg_data[avg_data$region %in% RL$V1,]
#-----
  region SN value
1   beta  1    32
2  alpha  2    44
3   beta  3    55

That's what I'd feed to split if you want to drop atp.

The approach above may be overkill if you are just wanting to plot. Here's an example using sapply to iterate through each level of region and make a plot:

sapply(unique(x$region), function(z) 
  plot(x[x$region == z,"value"], main=z[1]))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Very much for this idea of using sapply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.