遍历列并在R中复制数据

时间:2018-09-13 07:32:52

标签: r loops

我正在尝试遍历各列,如果该列是一整年,则应重复四次,然后重命名为四分之一

所以

@model IEnumerable<CmsShoppingCart.Models.ViewModels.Shop.ProductVM>

@{
    ViewBag.Title = ViewBag.CategoryName;
}

<h2>@ViewBag.CategoryName</h2>

@using (Html.BeginForm("Index", "Shop", FormMethod.Post))
{
    <div>
        Search By Products @Html.TextBox("searchString")
        <input id="Submit1" type="submit" value="Filter" />
    </div>
}

<table class="table">
    <tr>
        <th>
            Name
        </th>
        <th>
            Description
        </th>
        <th>
            Price
        </th>
        <th>
            Image
        </th>
        <th></th>
    </tr>

@foreach (var item in Model)
{

    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)

                </td>
        <td>
            @Html.DisplayFor(modelItem => item.Description)
        </td>
        <td>
            @Html.ActionLink("Price", "Category", new { SortOrder = ViewBag.Price })
            $@Html.DisplayFor(modelItem => item.Price, new { SortOrder = ViewBag.Price })

        </td>
        <td>
            <a href="/shop/product-details/@item.Slug">
                <img src="/Images/Uploads/Products/@item.Id/Thumbs/@item.ImageName" />
            </a>
        </td>
        <td>
            <a href="/shop/product-details/@item.Slug">Details</a>
        </td>
    </tr>
}

</table>

应该变成这个:

2000   Q1-01   Q2-01   Q3-01
   1       2       3       3    

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我们可以使用stringr::str_detect查找4位数字的姓氏,然后从这些列中获取最后两位数字

library(dplyr)
library(tidyr)
library(stringr)
df %>% gather(key,value) %>% group_by(key) %>% 
       mutate(key_new = ifelse(str_detect(key,'\\d{4}'),paste0('Q',1:4,'-',str_extract(key,'\\d{2}$'),collapse = ','),key)) %>% 
       ungroup() %>% select(-key) %>% 
       separate_rows(key_new,sep = ',') %>% spread(key_new,value)

PS:我希望您没有很大的数据集