r 中多列的 rowsum

标签 r dataframe for-loop rowsum

我可以通过 catVariables 中的分类列中的级别来计算 target 列的总和。但是,我不想在 for 循环中执行此操作,而是想立即将其应用于所有分类列。 For 循环将使代码运行时间更长,并且以向量化方式执行会更快。

# Data
col1 <- c("L", "R", "R", "L", "R", "L", "R", "L")
col2 <- c("R", "R", "R", "L", "L", "R", "L", "R")
col3 <- c("L", "-", "L", "R", "-", "L", "R", "-")
target <- c(1, 0, 0, 1, 1, 0, 1, 0)



dat <- data.frame("col1" = col1, "col2" = col2, "col3" = col3, "target" = target)

dat[sapply(dat, is.character)] <- lapply(dat[sapply(dat, is.character)], as.factor)
catVariables <- names(Filter(is.factor, dat))



# test
col1 <- c("L", "R", "R", "L", "R", "L", "R", "L")
col2 <- c("R", "R", "R", "L", "L", "R", "L", "R")
col3 <- c("L", "-", "L", "R", "-", "L", "R", "-")
target <- c(1, 0, 0, 1, 1, 0, 1, 0)

test_dat <- data.frame("col1" = col1, "col2" = col2, "col3" = col3, "target" = target)



for (col in catVariables){
ratios <- rowsum(dat[["target"]], dat[[col]])/sum(dat[["target"]])
print(ratios)
dat[[col]] <- ratios[match(dat[[col]],names(ratios[,1]))]
test_dat[[col]] <- ratios[match(test_dat[[col]], names(ratios[,1]))]
}

最佳答案

我们可以使用acrossdplyrrowsum在多列上

library(dplyr)
dat %>% 
  mutate(across(all_of(catVariables), 
     ~ {tmp <- rowsum(target, .x)/sum(target);
  tmp[match(.x, row.names(tmp))]}))

-输出

   col1 col2 col3 target
1  0.5 0.25 0.25      1
2  0.5 0.25 0.25      0
3  0.5 0.25 0.25      0
4  0.5 0.75 0.50      1
5  0.5 0.75 0.25      1
6  0.5 0.25 0.25      0
7  0.5 0.75 0.50      1
8  0.5 0.25 0.25      0

或者使用 test_dat/train data ('dat'),一个选项是循环 test_dat ,使用列名称 ( cur_column() ) 从 'dat' 中提取相应的列来计算 rowsum按组,然后match 'test_dat' 列值和输出的行名称以扩展数据

test_dat %>% 
  mutate(across(all_of(catVariables), 
     ~ {tmp <- rowsum(dat[["target"]], dat[[cur_column()]])/sum(dat[["target"]]);
  tmp[match(.x, row.names(tmp))]}))
  col1 col2 col3 target
1  0.5 0.25 0.25      1
2  0.5 0.25 0.25      0
3  0.5 0.25 0.25      0
4  0.5 0.75 0.50      1
5  0.5 0.75 0.25      1
6  0.5 0.25 0.25      0
7  0.5 0.75 0.50      1
8  0.5 0.25 0.25      0

关于r 中多列的 rowsum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71326644/

相关文章:

r - 填充 R data.frame 中每行中缺失的元素

Python:在列表中存储多个数据帧

python - 如何有条件地跳过 python 中 for 循环中的迭代步骤数?

r - 根据数据框中的公共(public)标识符和特定列按比例划分行值

R_using nlsLM() 有约束

r - knitr 的 kable 将 2.29e-30 打印为 "0"

dataframe - PySpark - 删除具有重复值且没有列顺序的行

c - 在for循环中填充二维数组

C++ 显示 char while 循环行

r - 如何在R中替换下划线后的字符串