1

I want to loop through the rows in a r dataframe (df1) and create columns based on the variable values (v1) on each row. V1 is a column name on the dataframe df1. What I want to do is add a column using the name V1 onto df2. Variable v1 is of the data type <date> and the values will all be dates.

This is what I tried

  for(row in 1:nrow(df1)){
    df2 %>%
      mutate(row$v1 == "value")
  }

3 Answers 3

1

Here's my answer

for(row in 1:nrow(df1)){
  colname <- df1[row, "v1"]
  df2[,colname] <- "value"
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Had to convert the colname into Character format since v1 was a date for(row in 1:nrow(df1)){ colname <- as.character(df1[row, "v1"]) df2[,colname] <- "value" } ```
0

You could do this directly without a loop :

df2[as.character(df1$v1)] <- 'value'

Comments

0

We can also use

library(dplyr)
df2 %>%
   mutate_at(vars(as.character(df1$v1)), 'value')

Comments

Your Answer

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