簡體   English   中英

帶向量條件的行總和

[英]Row sum with vector condition

我有一個data.frame看起來像這樣:

              V1             V2             V3
1            143            143            143
2            141            141            143
3            195            195            141
4            121            121            121
5            142            142            142

我想使用rowSums來計算一組值在一行中出現的次數,例如值c(141, 143) ,因此答案將按行計算此向量中值的出現次數:

3, 3, 1, 0, 0

想知道為什么這種使用%in%的方法沒有按預期工作:

rowSums(df[df %in% c(141, 143)], na.rm = T))

謝謝!

試試這個apply()方法:

#Code
apply(df,1,function(x) sum(x %in% c(141, 143)))

Output:

1 2 3 4 5 
3 3 1 0 0 

使用的一些數據:

#Data
df <- structure(list(V1 = c(143L, 141L, 195L, 121L, 142L), V2 = c(143L, 
141L, 195L, 121L, 142L), V3 = c(143L, 143L, 141L, 121L, 142L)), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5"))

檢查 output if df %in% c(141, 143) ... 並考慮 data.frame 實際上是一個列表。

這是一個替代方案:

rowSums(df == 141 | df == 143)

sapply中可能更快。

rowSums(sapply(dat, `%in%`, c(141, 143)))
# [1] 3 3 1 0 0

甚至更快(盡管看起來很奇怪)。

rowSums(t(do.call(rbind, lapply(dat, `%in%`, c(141, 143)))))
# [1] 3 3 1 0 0

基准:

Unit: microseconds
                                                         expr     min       lq      mean  median       uq      max neval cld
                             rowSums(dat == 141 | dat == 143) 143.643 147.8535 155.86417 151.807 158.6965  227.584   100   b
                    rowSums(sapply(dat, `%in%`, c(141, 143)))  52.048  54.0900  58.10532  55.365  56.7685  181.658   100  a 
 rowSums(t(do.call(rbind, lapply(dat, `%in%`, c(141, 143)))))  37.505  39.8015  42.94497  41.077  42.2255  144.663   100  a 
           apply(dat, 1, function(x) sum(x %in% c(141, 143))) 149.256 153.5940 183.03378 155.890 160.2270 2560.057   100   b

數據:

dat <- structure(list(V1 = c(143L, 141L, 195L, 121L, 142L), V2 = c(143L, 
141L, 195L, 121L, 142L), V3 = c(143L, 143L, 141L, 121L, 142L)), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5"))

rowwise/c_across選項

library(dplyr)
df %>%
    rowwise %>% 
    mutate(Sum = sum(c_across(everything()) %in% c(141, 143)))
# A tibble: 5 x 4
# Rowwise: 
#     V1    V2    V3   Sum
#  <int> <int> <int> <int>
#1   143   143   143     3
#2   141   141   143     3
#3   195   195   141     1
#4   121   121   121     0
#5   142   142   142     0

數據

df <-  structure(list(V1 = c(143L, 141L, 195L, 121L, 142L), V2 = c(143L, 
141L, 195L, 121L, 142L), V3 = c(143L, 143L, 141L, 121L, 142L)),
class = "data.frame", row.names = c("1", 
"2", "3", "4", "5"))

暫無
暫無

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

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