1

my dataframe looks like this.

df <- read.table(text="
                 column1  column2   column3
    1            3        2         1
    1            3        2         1 
", header=TRUE)

I need to subtract last 2 columns from first. For counting that columns I´d use rowSums(summary[,1:3]) but I don´t know how to subtract this columns. Note that I can´t just write my code like this since I don´t know column names.

`result <- df %>% 
mutate(result = rowSums(column1, - column2, - column3))` 
Sklenicka
  • 595
  • 2
  • 4
  • 16

1 Answers1

2

We can subset the data to remove the first column (.[-1]), get the rowSums and subtract from 'column1'

library(tidyverse)
df %>%
    mutate(result = column1 - rowSums(.[-1]))
#   column1 column2 column3 result
#1       3       2       1      0
#2       3       2       1      0

If there are more columns and want to select the last two columns

df %>%
    mutate(result = column1 - rowSums(.[tail(names(.), 2)]))

If we have only the index of the columns that are involved in the operation

df %>% 
    mutate(result = .[[1]] - rowSums(.[c(2, 3)]))

data

df <- structure(list(column1 = c(3L, 3L), column2 = c(2L, 2L), column3 = c(1L, 
 1L)), class = "data.frame", row.names = c(NA, -2L))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • But what if I know just index of that column1 but now its name? – Sklenicka Dec 28 '18 at 02:39
  • @Sklenicka In that case use that as a vector i.e. `df %>% mutate(result = column1 - rowSums(.[c(2, 3)]))` – akrun Dec 28 '18 at 02:40
  • Are you saying that you know only index of all the columns. Then try `df %>% mutate(result = .[[1]] - rowSums(.[c(2, 3)]))` – akrun Dec 28 '18 at 02:41