给出以下数据框:
df <- data.frame("a" = 1:5, "b" = 2:6, "c" = 3:7, "d" = c(NA,1,1,0,0))
如果a
列中的值是b
,如何将c
,NA
和d
列中的值更改为NA
或0
?我可以轻松地将其用于单个列,例如df[,3][df$d==0|is.na(df$d)] <- NA
,但在跨多个列工作时遇到了麻烦。我非常感谢使用基数R或dplyr
的解决方案。谢谢
答案 0 :(得分:3)
你是这个意思吗?
function getDef() {
let cart = {
VS5: [
{
num: 3,
price: 6.99,
},
{
num: 5,
price: 8.99,
},
],
MB11: [
{
num: 2,
price: 9.95,
},
{
num: 5,
price: 16.95,
},
{
num: 8,
price: 24.95,
},
],
CF: [
{
num: 3,
price: 5.95,
},
{
num: 5,
price: 5.95,
},
{
num: 9,
price: 16.99,
},
],
};
return cart;
}
function getInput() {
let input = [
{VS5: 10},
{MB11: 14},
{CF: 13},
];
return input;
}
function backtrack() {
}
function main() {
let inputArr = getInput();
let def = getDef();
for(let i=0; i<inputArr.length; i++) {
let item = inputArr[i];
let key = Object.keys(item)[0];
let val = item[key];
let defSubArr = def[key];
console.log('-----------');
console.log('key: ' + key);
console.log('val: ' + val);
//console.log(defSubArr);
console.log('==');
for(let j=0; j<defSubArr.length; j++) {
let num = defSubArr[j].num;
let price = defSubArr[j].price;
console.log('num: ' + num);
console.log('price: ' + price);
backtrack(val, num, price);
}
}
}
// -- run --
main();
或者在cols <- c("a", "b", "c")
df[is.na(df$d) | df$d == 0, cols] <- NA
df
# a b c d
#1 NA NA NA NA
#2 2 3 4 1
#3 3 4 5 1
#4 NA NA NA 0
#5 NA NA NA 0
dplyr