Home > Net >  Adjust a function's argument in R
Adjust a function's argument in R

Time:03-21

How do I put all XMR arguments from below dataset as argument inside a function at once?

I could do like this:

f1 <- function(X1,X2,X3,X4, XM1, XMR0, XMR01, XMR02, XMR03, XMR4){
  
  x2<-df1 %>% select(starts_with("XMR"))
  x2<-cbind(df1, setNames(df1$XM1 - x2, paste0(names(x2), "_PA")))
  x3<-select(x2,X1,X2,X3,X4,XM1,ends_with("PA"))

return(x3)
 }

However, if I had a lot of XMR, it would be bad to put several XMR. Is there any easier way to do it?

  df1 <- structure(
  list(
    X1 = c(1, 1, 1, 1),
    X2 = c("4","3","1","2"),
    X3 = c("1", "2","3","2"),
    X4 = c("1", "2","3","2"),
    XM1 = c(200, 300, 200, 200),
    XMR0 = c(300, 300, 300, 300),
    XMR01 = c(300, 300, 300, 300),
    XMR02 = c(300,300,300,300),
    XMR03 = c(300,300,300,300),
    XMR04 = c(300,250,350,350)),row.names = c(NA, 4L), class = "data.frame")

CodePudding user response:

It would be easier with do.call (assuming the arguments to the functions are in the same order as the columns of the data)

do.call(f1, as.list(colnames(df1)))
 X1 X2 X3 XM1 XMR0_PA XMR01_PA XMR02_PA XMR03_PA XMR04_PA
1  1  4  1 200    -100     -100     -100     -100     -100
2  1  3  2 300       0        0        0        0       50
3  1  1  3 200    -100     -100     -100     -100     -150
4  1  2  2 200    -100     -100     -100     -100     -150

The function can be also written as

f2 <- function(data){ 
  
  data %>% 
     transmute(across(matches("^X\\d $")),
      XM1, across(starts_with("XMR"), ~ XM1 - .x, 
        .names = "{.col}_PA" )) 
  }

and then we use as

> f2(df1)
  X1 X2 X3 XM1 XMR0_PA XMR01_PA XMR02_PA XMR03_PA XMR04_PA
1  1  4  1 200    -100     -100     -100     -100     -100
2  1  3  2 300       0        0        0        0       50
3  1  1  3 200    -100     -100     -100     -100     -150
4  1  2  2 200    -100     -100     -100     -100     -150
  •  Tags:  
  • r
  • Related