Reputation: 7517
In function foo
below, argument long
accepts a vector of binary T/F
input. Given the data.frame
called out
in my function, I want my function to add a column named "long"
and populate it with T
s for the T
inputs and F
for the F
inputs from "long"
argument. Also, I want my function to add a column named "short"
and populate it with F
s for the T
inputs, and T
for the F
inputs from "long"
argument.
Here is what I have tried with no success:
foo <- function(d, long){
nm <- if(!missing(long) & long) "long" else if(!missing(long) & !long) "short" # problematic
out <- data.frame(d)
if(!missing(long))out[nm] <- long ## problematic
return(out)
}
foo(d = 1:3, long = c(T, F,T))
Upvotes: 1
Views: 36
Reputation: 389175
You could do
foo <- function(d, long){
data.frame(d, long = long, short = !long)
}
foo(d = 1:3, long = c(T, F,T))
# d long short
#1 1 TRUE FALSE
#2 2 FALSE TRUE
#3 3 TRUE FALSE
Or if you want output as "T"
and "F"
only
foo <- function(d, long){
out <- data.frame(d, long = long, short = !long)
transform(out, long = substr(long, 1, 1), short = substr(short, 1, 1))
}
foo(d = 1:3, long = c(T, F,T))
# d long short
#1 1 T F
#2 2 F T
#3 3 T F
Upvotes: 1