有没有办法在R中的两个数据帧上应用具有多个参数的函数?

我想编写一个函数来用“其他”data.frame 中的相应值替换“values”data.frame 中“+”的值。

values <- data.frame(A = c("banana", "orange", "apple", "pear", "+"),
                 B = c("apple", "+", "banana", "melon", "orange"))

others <- data.frame(A = c("", "", "", "", "apple"),
                     B = c("", "pear", "", "", ""))

names <- c("A", "B")

#function to replace values of "+" with corresponding value in other data.frame
replace_with_other <- function(x, y) {
  ifelse(x == "+", y, x)
}

这个函数是这样工作的,但我不知道如何迭代“名称”中的所有值。

#this works and gives the desired output
replace_with_other(values$A, others$A)

#but when I try to iterate over all the names, I get an error message.
map(names, replace_with_other(values, others))

对于名字“A”,我正在寻找的输出是

"banana" "orange" "apple"  "pear"   "apple" 

有人有想法吗?

回答

这对你有用吗?

> Map(replace_with_other, values[names], others[names])
$A
[1] "banana" "orange" "apple"  "pear"   "apple"

$B
[1] "apple"  "pear"   "banana" "melon"  "orange"```


以上是有没有办法在R中的两个数据帧上应用具有多个参数的函数?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>