如何乘以常数,然后跨行求和

时间:2019-09-05 00:40:29

标签: r dplyr subset multiple-columns constants

我遇到了一个问题,即将3列乘以3个不同的常数(分别为2,3,4),然后在应用转换后将每一行相加。

我正在使用dplyr

variable <- df %>% transmute(df, sum(col1, col2*2, col3*3, col4*4))

3 个答案:

答案 0 :(得分:2)

我们可以做到

library(dplyr)

df %>%
  mutate(a = a * 2, 
         b = b * 3, 
         c = c * 4, 
         total = a + b + c) 

#   a  b  c total
#1  2 18 44    64
#2  4 21 48    73
#3  6 24 52    82
#4  8 27 56    91
#5 10 30 60   100

使用rowSums

df %>%
  mutate(a = a * 2, 
         b = b * 3, 
         c = c * 4) %>%
  mutate(total = rowSums(.))

重要的是要注意,如果我们使用的是rowSums,则需要将其包含在新的mutate调用中,而不要包含在同一调用中,否则它将sum原始{{1} },而不是更改的。

或在基数R

df

数据

df1 <- transform(df, a = a*2, b = b * 3, c = c *4)
df1$total <- rowSums(df1)

答案 1 :(得分:2)

base R中,我们可以使用%*%

df$total <- c(as.matrix(df) %*% 2:4)
df
#  a  b  c total
#1 1  6 11    64
#2 2  7 12    73
#3 3  8 13    82
#4 4  9 14    91
#5 5 10 15   100

或与crossprod

df$total <- c(crossprod(t(df), 2:4))

-

或与tidyverse

library(tidyverse)
map2(df, 2:4, ~ .x * .y) %>%
     reduce(`+`) %>%
     bind_cols(df, total = .)

数据

df <- data.frame(a = 1:5, b = 6:10, c = 11:15)

答案 2 :(得分:1)

AttributeError: module 'keras.backend' has no attribute 'image_dim_ordering'

尝试尝试。

  1. 添加variable <- df %>% rowwise() %>% mutate(new_var = sum(col1, col2*2, col3*3, col4*4)) 以对每一行进行数据分析
  2. 使用rowwise()获得新的计算结果