简体   繁体   中英

in R: how to take value from Nth cell and subtract from every cell in Nth column

Let's say I have a data set that looks as follows:

subvalues <- c(1:10)

df <- data.frame(x = rpois(40,2), y = rpois(40,2), z = rpois(40,2), q = rpois(40,2), t = rpois(40,2))

I want to take the value from the first cell of subvalues and subtract that from every cell in x, then the 2nd cell of subvalues and subtract it from every cell in z, and so on - Thereby generating a new dataframe where every row in x, z etc. are new values (original value minus value from selected cell of subvalues )

note that my actual data set is thousands of rows and columns, so brute-forcing it is not an option.

What i am looking for is

1: A function/loop for picking out first the first cell of subvalues (for further use), then on the 2nd loop picking out the 2nd cell, etc.

2: How to apply the value from the selected cell from subvalues on every cell in a given column (subtract first row of subvalue from every row in column x, then subtract 2nd row of subvalues from every row in column z, etc)

From what I have gathered I need to use the mutate_at function but I have no idea how to create a function that selects first the first row of subvalues, then the 2nd, etc.

The desired output would be 5 columns with every row a new value (product of original values in the rows minus the particular subvalue selected for that column) - new columns = x2, y2, z2, q2, t2:

Q2 Y2 z2 q2....etc

xa-1 ya-2 za-3 qa-4
xb-1 yb-2 zb-3 qb-4
xc-1 yc-2 zc-3 qc-4
xe-1 yd-2 zd-3 qd-4
xf-1 ye-2 ze-3 qe-4
xg-1 yf-2 zf-3 qf-4
xh-1 yg-2 zg-3 qg-4

Any help is much appreciated

It could be done with outer

outer(df$x, subvalues, `-`)
outer(df$z, subvalues, `-`)

In a loop, it would be

lapply(df[c('x', 'z')], outer, subvalues, `-`)

If we want to do this in tidyverse

library(dplyr)
library(purrr)
df %>%
    mutate_at(vars(x, z), list(newcol =  ~map(., ~ .x - subvalues))) %>%
    unnest(ends_with('newcol')) %>% 
    cbind(subvalues) 

Or with crossing

imap(df %>%
       select(x, z), ~ crossing(!! .y := .x, subvalues) %>% 
                          mutate(!! str_c('diff', .y) := reduce(., `-`))) %>% 
   bind_cols

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM