'Binary variables for several columns

Is there a way to create binary variables for multiples columns based on the same condition?

This is my code:

spei.grid.final.AEZ$TropicsLH.Bi = ifelse(spei.grid.final.AEZ$`TropicsLH\r\n`> 0,c(1), c(0))

For each column, I would like a new binary column which equals 1 if their value in the row (gid) is superior to 0. Otherwise, 0.

dput(head(spei.grid.FS))

structure(list(gid = c("100467", "100467", "100467", "100467", 
"100467", "100467"), Perennial_mixed_farming_system = c(0, 0, 
0, 0, 0, 0), Fish_based_farming_system = c(1204.640632337, 1204.640632337, 
1204.640632337, 1204.640632337, 1204.640632337, 1204.640632337
), Pastoral_farming_system = c(0, 0, 0, 0, 0, 0), Maize_mixed_farming_system = c(0, 
0, 0, 0, 0, 0), Agropastoral_farming_system = c(0, 0, 0, 0, 0, 
0), Highland_mixed_farming_system = c(0, 0, 0, 0, 0, 0), Arid_pastoral_oasis_farming_system = c(1045.59475465, 
1045.59475465, 1045.59475465, 1045.59475465, 1045.59475465, 1045.59475465
), Humid_lowland_tree_crop_farming_system = c(0, 0, 0, 0, 0, 
0), Large_scale_irrigated_farming_system = c(0, 0, 0, 0, 0, 0
), Root_and_tuber_crop_farming_system = c(0, 0, 0, 0, 0, 0), 
    Highland_perennial_farming_system = c(0, 0, 0, 0, 0, 0), 
    Forest_based_farming_system = c(0, 0, 0, 0, 0, 0), Cereal_root_crop_mixed_farming_system = c(0, 
    0, 0, 0, 0, 0)), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))


Solution 1:[1]

consider using new operator that returns a pointer to the heap allocated object, so your object is no-longer a temporary value.

Piece* pieces[] = {
    new King{square},
    new Queen{square},
    new Rook{square}
};

but you have to call delete on every item in the array before the array is deleted so you won't have a memory leak.

instead i'd recommend using shared pointers (or unique pointers), and make your array an array of shared pointers, and use make shared instead of new, so you don't have to worry about memory leaks.

std::shared_ptr<Piece> pieces[] = {
    std::make_shared<King>(square),
    std::make_shared<Queen>(square),
    std::make_shared<Rook>(square)
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1