[英]Sum row values of a data frame using R - where each value in the row is evaluated against a condition
[英]Percentage of each row that meet a condition in a data frame in R
我有一個數據框(調用“dat”)和一個包含 6 個元素的向量(調用 v)
我想在數據框中添加6 個新列
第一個新列:每行中大於向量第一個元素的元素數
第二個新列:每行中大於向量第二個元素的元素數
第三個新列:每行中大於向量第三個元素的元素數
等等.....
dat<-data.frame(replicate(10,sample(0:6,50,rep=TRUE)))
v<-c(2,4,1,3,5,6)
謝謝
在基礎 R 中,您可以執行以下操作:
dat[paste0('greater_than_', v)] <- lapply(v, function(x) rowSums(dat >= x))
在purrr
中,您可以執行以下操作:
dat[paste0('greater_than_', v)] <- map(v, ~rowSums(dat >= .x))
我們可以通過這種方式使用tidyverse
library(dplyr)
library(purrr)
library(stringr)
map_dfc(v, ~rowSums(dat >= .x)) %>%
rename_all(~str_c('greater_than_', v)) %>%
bind_cols(dat, .)
或者在base R
中使用for
循環
for(i in seq_along(v)) dat[paste0('greater_than_', v[i])] <- rowSums(dat >= v[i])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.