1

I have a data frame with variables labeled var1-var38 and I am trying to multiply var1*var20-38 and add these new variables to the existing data frame. My issue is that I can create a string with var20, but it is not referring to var20 in the data frame. My code is as follows:

inter.data <- read.csv("interactions.csv", header = T, sep = ",")
a <- 20
while(a <= 38) {
 name <- paste("var", a, sep = "")
 inter.data[paste("var1*", name, sep="")] <- NA
 inter.data$var1*name <- (inter.data$var1)*(inter.data$name)
 a <- a+1
}

I have tried

inter.data <- read.csv("interactions.csv", header = T, sep = ",")
a <- 20
attach(inter.data)
while(a <= 38) {
 name <- paste("var", a, sep = "")
 inter.data[paste("var1*", name, sep="")] <- NA
 inter.data$var1*name <- (var1)*(name)
 a <- a+1
}

as well

1 Answer 1

2

I don't think you need a for loop for this. You can add the columns you are trying to create as follows. In this example, we have a dataframe with four columns, and we want to add the column var1*var3 and var1* var4

df = data.frame(var1=c(2,2,2),var2=c(1,2,3),var3=c(4,5,6),var4=c(7,8,9))

new_df <- df[,3:4] * df[,"var1"]
colnames(new_df) = paste0("var1*",colnames(new_df))
cbind(df,new_df)

output:

  var1 var2 var3 var4 var1*var3 var1*var4
1    2    1    4    7         8        14
2    2    2    5    8        10        16
3    2    3    6    9        12        18

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

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.