使用嵌套的lapply过滤条件并创建多个数据框

时间:2019-01-10 20:10:48

标签: r filter dplyr lapply

这是我的名为shipment的数据的示例:

shipment <- read.table(text = 'Week Org     Forecast       Actual Forecast.over..under Accuracy.. Int.Ext
24    1/22/2018 KNI      $5,095       $7,101              $(2,006)       139%    Int 
366  12/31/2018 DAN  $3,387,247   $1,907,435           $1,479,812         56%    Int ', header = T)

我想创建15个数据帧的列表,这些数据帧针对这两个向量分别对列OrgInt.Ext的所有可能组合进行了过滤。

int.ext <- c("Int","Ext","Total")
site <- c("BAL", "DAN", "LON", "STL", "WC")

当我运行下面的代码时,我得到一个列表,但是正确列出的唯一数据帧是Int.Ext值为“总计”的数据帧。应该为“ Int”或“ Ext”过滤的数据帧不包含任何行。

frames <- lapply(int.ext, function(i){ 
            lapply(site, function(j){ 
                filter(shipment, Org==j, Int.Ext==i)})
                      })

1 个答案:

答案 0 :(得分:1)

如果您愿意移出基数R,这可能会更简洁:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="personalityQuiz">
    <h3> What is your favorite food?</h3>
    <input type="radio" name="food" value="cat"> I only eat meat.<br>
    <input type="radio" name="food" value="horse">  I'm a strict vegetarian.<br>
    <input type="radio" name="food" value="dog">  I love all food!<br>

    <h3> What is your favorite hobby?</h3>
    <input type="radio" name="hobby" value="horse"> I was born to run.<br>
    <input type="radio" name="hobby" value="dog">  Anything with a ball.<br>
    <input type="radio" name="hobby" value="cat">  Naps<br>

    <h3> What scares you?</h3>
    <input type="radio" name="fear" value="dog"> Vacuum cleaners.<br>
    <input type="radio" name="fear" value="cat">  Water<br>
    <input type="radio" name="fear" value="horse">  Anything that moves!<br>

    <input type="submit" value="Submit">
</form>


<div class="result" id="cat">
    <h2> You are a cat! </h2>
</div>
<div class="result" id="dog">
    <h2> You are a dog! </h2>
</div>
<div class="result" id="horse">
    <h2> You are a horse! </h2>
</div>
<div class="result" id="fish">
    <h2> You are a fish! </h2>
</div>

或者,如果您确实需要将它们拆分为数据帧列表,也许

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.0</version>
</dependency>