简体   繁体   中英

mutating a dataframe using values from another dataframe as variable names in R

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")
  }

Here's my answer

for(row in 1:nrow(df1)){
  colname <- df1[row, "v1"]
  df2[,colname] <- "value"
}

You could do this directly without a loop:

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

We can also use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM