R:更新函数的输入变量



如何更新函数的输入变量

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)

是否有一个适当的方法来添加一个col输入df和更新输入变量?

谢谢你的帮助!

你可以做

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函数,结果将是这样的

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

相关内容

  • 没有找到相关文章