簡體   English   中英

R:根據另一個變量在數據框中添加行

[英]R: adding rows in a data frame depending on another variable

我正在嘗試做一種條件rowSums

我有一個數據框,其中四列包含1和0,另一個變量指示應添加哪些列以使行總計。

例如:

df <- matrix(rbinom(40, 1, 0.5), ncol = 4)
df <- as.data.frame.matrix(df)
df$group <- sample(c('12', '123', '1234'), 10, replace = T)

如果組是12 ,則應添加列V1:V2,如果123則V1:V3,如果1234則列V1:V4。

我嘗試過勞動密集型的方法:

df$total12 <- rowSums(df[,c('V1', 'V2')])
df$total123 <- rowSums(df[,c('V1', 'V2', 'V3')])
df$total1234 <- rowSums(df[,c('V1', 'V2', 'V3', 'V4')])
df$total <- ifelse(df$group == '12', df$total12,
                   ifelse(df$group == '123', df$total123, df$total1234))

有更簡單的方法嗎?

這是一個選項。 我們通過拆分'group'來創建行/列索引,根據索引提取'df'的值,並獲得按row索引分組的sum

lst <- strsplit(df$group, "")
i1 <- cbind(rep(seq_len(nrow(df)), lengths(lst)), as.integer(unlist(lst)))
df$total <- ave(df[-5][i1], i1[,1], FUN = sum)

這是使用switch功能的另一個選項。 這比一系列嵌套的ifelse語句更易讀,更容易擴展。

df$total<-sapply(1:length(df$group), function(i){switch(df$group[i], 
            "12"=rowSums(df[i, c('V1', 'V2')]),
            "123"=rowSums(df[i, c('V1', 'V2', 'V3')]),
            "1234"=rowSums(df[i, c('V1', 'V2', 'V3', 'V4')]))})

基本上,循環遍歷df $ group的元素並選擇要使用的正確公式。 如果您的數據集不是太長,那么性能應該是可以接受的。

暫無
暫無

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

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