synat
synat

Reputation: 27

Using loop to create the new variable from the ratio of the existing variable in the data-frame

I have recently learning loop and would like to apply it to my data analysis. I would like to use loop to create two new columns from the existing data frame:

Assum this is my dataframe

var1<- c(10, 12, 15, 34)
var2<- c(11, 17, 26, 45) 
var3<- c(14, 16, 46, 78)

df<- data.frame(var1, var2, var3)

I woul like to write a loop to create the two new columns which are the ratio of var4= var1/var2 and var5= va2/var3.

Write a for loop

df$var4= ""  # create empty column
df$var5=""   # create empty column

for (i in df) {
  var4= df$var1 / df$var2
  var5= df$var2 / df$var3
df.final= as.data.frame(df, var4, var5)
}

##Code not work at all.

Can anyone suggest how I can use loop in here. I would like to stick to loop not sth else. Hope you can guide

Kind Regards,

synat

Upvotes: 0

Views: 116

Answers (1)

Vishal A.
Vishal A.

Reputation: 1381

To traverse the rows of a data frame in R, you need to change the for loop in your code. Instead of i in df it should be i in 1:nrow(df). The code will look like this:

for (i in 1:nrow(df)) {
  df$var4 = df$var1 / df$var2
  df$var5 = df$var2 / df$var3
}

df.final <- df[c("var4", "var5")]
df.final

The output will look like this:

      var4      var5
1 0.9090909 0.7857143
2 0.7058824 1.0625000
3 0.5769231 0.5652174
4 0.7555556 0.5769231

EDIT: As Limey has suggested, there is no need for a for loop to achieve this result as it is redundant to do so. One can simply do this using following:

df$var4 <- df$var1 / df$var2
df$var5 <- df$var2 / df$var3

It will give you the same result.

Upvotes: 1

Related Questions