总结相似的列

时间:2018-05-10 06:51:54

标签: r plyr

我想对具有相似名称的列进行求和。我知道plyr有一个numcolwise函数,它是否有相似的列?

     C1    C1      T1      T1
n1   2     21     12       12
n2   12    12     34       45


      C1   T1
n1    23   24
n2    22   79

1 个答案:

答案 0 :(得分:3)

我会使用sapply执行此操作,循环unique df sapply(unique(names(df)), function(x) rowSums(df[names(df) %in% x])) # C1 T1 #n1 23 24 #n2 24 79 名称,并收集所有具有相似名称的列并对其进行行总和。

rownames

另一种选择是转置数据框并使用rowsum作为分组变量,并使用rowsum(t(df), rownames(t(df))) # n1 n2 #C1 23 24 #T1 24 79 按组分组。

// show the shows with highest ranking
fetch('https://api.tvmaze.com/shows')
    .then(blob => blob.json())
    .then(json => {
        const topTenShows = json
        .filter(show => show.rating.average) 
        .sort((a, b) => a.rating.average > b.rating.average ? -1 : 1) 
        .slice(0, 9) // tar element 0-9 i arrayen

    return topTenShows
  })
  .then(shows => {
    const app = document.getElementById('app')

    app.innerHTML = shows.map(show => `
      <div class="col-sm movie-content">
        <img src="${show.image.medium}">
        <div class="movie-info">
          <h5>${show.name}</h5>
          <span>Rating: ${show.rating.average}</span>
          <br />
          <span>Rating: ${show.genres}</span>
        </div>
      </div>

    `).join()
  })

// show the search results
function searchTvAmaze ({ target }) {
    fetch(`https://api.tvmaze.com/search/shows?q=${target.value}`)
        .then(blob => blob.json())
        .then(shows => {
            const app = document.getElementById('app')

        app.innerHTML = shows.map(show => `
          <div class="col-sm movie-content">
            <img src="${show.image.medium}">
            <div class="movie-info">
              <h5>${show.name}</h5>
              <span>Rating: ${show.rating.average}</span>
              <br />
              <span>Rating: ${show.genres}</span>
            </div>
          </div>

        `).join()
      })
  }

  const inputSearchField = document.querySelector('.inputSearchField')
  inputSearchField.addEventListener('keydown', searchTvAmaze)