0

I have the following data:

Letters <- c("A","B","C")
Numbers <- c(1,0,1)
Numbers <- as.integer(Numbers)

Data.Frame <- data.frame(Letters,Numbers)

I want to create a Dummy Variable for the Letters and wrote the following for-loop:

for(level in unique(Data.Frame$Letters)){Data.Frame[paste("", level, sep = "")]
<- ifelse(Data.Frame$Letters == level, 1, 0)}

Is there a way to vectorize this for-loop? Is the following use of dcast alredy vectorized?

dt <- data.table(Letters,Numbers)
dcast.data.table(dt, Letters+Numbers~Letters,fun.aggregate=length)

1 Answer 1

1

You could use outer

cbind(Data.Frame, +outer(Letters, setNames(nm=Letters), "=="))
#   Letters Numbers A B C
# 1       A       1 1 0 0
# 2       B       0 0 1 0
# 3       C       1 0 0 1
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much. And this is vectorized because the outer function is applying "==" to the two vectors Letters and setNames(nm=Letters)?
outer is a vectorized function, yes. (i.e. there are no internal loops)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.