'Mutating columns with reduce2 and rlang

I am trying the following:

library(tidyverse)
library(rlang)

df <- data.frame(a = 1:2)

reduce2(list(df, df, df), letters[2:3], ~ mutate(.x, !!(.y) := 2:3))
#> Error in local_error_context(dots = dots, .index = i, mask = mask): promise already under evaluation: recursive default argument reference or earlier problems?

I do know many ways of mutating columns to a dataframe, but I am trying to learn rlang.

The expected output:

  a b c
1 1 2 2
2 2 3 3


Solution 1:[1]

A method to combine purrr::reduce() and rlang is:

library(dplyr)
library(purrr)

reduce(letters[2:3], ~ .x %>% mutate(!!.y := 2:3), .init = df)

#   a b c
# 1 1 2 2
# 2 2 3 3

where the trick is to assign df to the argument .init.

Solution 2:[2]

I am sure you are aware that you can do df[letters[2:3]] <- 2:3 to achieve the same output but I don't think this is what you are looking for.

To use purrr and rlang you may use -

library(dplyr)
library(purrr)

bind_cols(df, map_dfc(letters[2:3], ~df %>% transmute(!!.x := 2:3)))

#  a b c
#1 1 2 2
#2 2 3 3

And another way would be -

map(letters[2:3], ~df %>% mutate(!!.x := 2:3)) %>% reduce(inner_join, by = 'a')

Solution 3:[3]

To me, module inside the parented to the script:

local Functions = {}
function Functions.findOpenBase(plr)
    -- check it first.
    if plr.alreadyOwnsBase.Value == false then
        local bases = workspace.Bases
        for i,v in pairs(bases:GetChildren()) do
            print("Searching..")
            if v:IsA("Part") then
                if v.Owner.Value ~= nil then
                    print("Base found!")
                    v.Owner.Value = plr.Name
                    plr.alreadyOwnsBase.Value = true
                    -- get it, jump the loop
                    break
                end
            else
                print("cannot claim another base")
            end
        end
    end
    -- and plr.alreadyOwnsBase.Value is the flag of the result
    if plr.alreadyOwnsBase.Value == false then
        warn("error")
        plr:Kick("error finding base, Please Rejoin.")
    end
end

return Functions

and the handler script:

local module = require(script.Functions)

game.Players.PlayerAdded:Connect(function(plr)
    local alreadyOwnsBase = Instance.new("BoolValue", plr)
    alreadyOwnsBase.Name = "alreadyOwnsBase"
    alreadyOwnsBase.Value = false
    if plr then
        module.findOpenBase(plr)
        -- check the flag
        if plr.alreadyOwnsBase.Value then
            print(plr.Name)
        end
    end
end)

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
Solution 2 Ronak Shah
Solution 3