簡體   English   中英

跨多個列的分組功能

[英]Grouped function across multiple columns

我試圖通過一個系數找到多個列中的最小值,然后從原始數據框中減去該最小值。 所以說我有這個數據:

testdata <-  data.frame(
  category=factor(rep(c("a","j"),each=6,times=8)), 
  num1=(sample(0:15, 96, replace=TRUE)) + 5, 
  num2=(seq(1:96))
)

我正在尋找每個“類別”(a和j)的num1和num2列的最小值。 在現實生活中,我的因子變量更為復雜,並且具有大量的數字變量。

我能做的最好的事情是這樣的:

test2 <- by(testdata, testdata[,"category"], function(x){
  y <- as.data.frame(apply(x[, c(2:3)], 2, min))
})

並將其重新組合在一起:

test3 <- do.call(rbind, lapply(test2, data.frame, stringsAsFactors=FALSE))

這似乎可行,但是我對如何按組減去該最小值有些困惑。 我想用sqldf完成的大致想法:

testdata4 <- sqldf("select a.category, 
                   a.num1-b.num1 as num1, 
                   a.num2-b.num2 as num2 
                   from testdata a left join testdata3 b 
                   on a.category = b.category")

盡管我不想指定每個新變量。 有什么想法嗎?

使用tidyverse

library(tidyverse)
# Use set.seed(x) before generating data for future Q's to allow easy checks
#   of the desired output
set.seed(123)

testdata <-  data.frame(
    category=factor(rep(c("a","j"),each=6,times=8)), 
    num1=(sample(0:15, 96, replace=TRUE)) + 5, 
    num2=(seq(1:96))
)

# Generate those same minimums (note that you don't have to do this, just
# showing that you get the same results as your original code)
testdata %>%
    group_by(category) %>%
    summarize(num1 = min(num1), num2 = min(num2))

# Subtract them from the actual data
testdata %>%
    group_by(category) %>%
    mutate(num1_normed = num1 - min(num1),
           num2_normed = num2 - min(num2))

或者,如果您有很多列,並希望將其自動應用於所有列:

# Applies the function to all columns except 'category', the group_by column
testdata %>%
    group_by(category) %>%
    mutate_all(function(x) { x - min(x)})

以下是一些僅使用基數R的方法ave方法維護行的順序。

1)通過 by問題中的用法使用by但帶有sweep

Sweep <- function(x) cbind(x[1], sweep(x[-1], 2, apply(x[-1], 2, min), "-"))
do.call("rbind", by(testdata, testdata[[1]], Sweep))

2)除第一個列外,對其他列使用ave ,使用x-min(x)給出列L的列表,然后,由於ave保持順序,在第二行中用其修改內容替換原始列。

L <- lapply(testdata[-1], function(x) ave(x, testdata[[1]], FUN = function(x) x - min(x)))
replace(tesdata, -1, L)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM