r - R:更新 function 中的输入变量

如何更新 function 的输入变量

df1 = data.frame(State = c('Arizona AZ','Georgia GG', 'Newyork NY','Indiana IN','Florida FL'), Score=c(62,47,55,74,31), id=c(1,2,3,4,5))
df1

df2 = data.frame(State = c('Arizona AZ','Georgia GG', 'Newyork NY','Indiana IN'), Score2=c(10,7,5,4), id=c(1,2,3,4))
df2
CalcPerc <- function(x, ins) {
  
  # 1) Subset + cbind
  y  <- subset(ins, id %in% x$id)
  
  z <- merge(x, y, by = c('State', 'id'))
  
  x1 <- 100*(z$Score2/z$Score)
  
  # Output - write in new col of x (input variable)
    print(x1)
    x$Percent <- x1 # Not working
}

CalcPerc(x= df2, ins = df1)

是否有适当的方法将列添加到输入 df 并更新输入变量?

谢谢你的帮助!

回答1

你可以做

library(dplyr)    
CalcPerc <- function(x, ins) {
      
    x %>% 
      left_join(ins %>% filter(id %in% x$id), by =  c('State', 'id')) %>% 
      mutate(Percent = round(Score2/Score*100,2)) %>% 
      pull(Percent)
    }
      
    CalcPerc(x= df2, ins = df1)

这给了你

[1] 16.13 14.89  9.09  5.41

如果没有 pull function,结果将如下所示

CalcPerc(x= df2, ins = df1)
       State Score2 id Score Percent
1 Arizona AZ     10  1    62   16.13
2 Georgia GG      7  2    47   14.89
3 Newyork NY      5  3    55    9.09
4 Indiana IN      4  4    74    5.41

相似文章

最新文章