w.kye
w.kye

Reputation: 17

Creating a new variable through loops in R

Here is a made up dataset that consist of 1) the number of black marbles 2) the number of white marbles and 3) total marbles

white<- c(5, 6,3,5, 9)
black<- c(1, 3,7,5,2)
total<- c(6,9,10,10,11)
data<- data.frame(white, black, total)

If I wanted to make a loop that created two new variables perwhite, which is white/total and perblack which is black/total, what would I need to do?

Here is what i've tried so far

variables<- list("white","black")
newnames<- list("perwhite", "perblack")
for (i in 1:2) {
  data$newnames[i]<- data[,variables[[i]]]/data$total
}

I think the problem in the current syntax is the when I am trying to create a new column in the dataset.

Thank you!

Upvotes: 0

Views: 62

Answers (1)

Artem Sokolov
Artem Sokolov

Reputation: 13691

for( i in setdiff( names(data), "total" ) )
    data[paste0( "per", i )] <- data[i] / data["total"]

NOTE: I would caution against using data as a variable name, because it's a name for one of the built-in functions.

Upvotes: 1

Related Questions