Doug Fir Doug Fir - 3 years ago 179
R Question

Add new features to a df based on a chr vector and make all values 0

I have a vector

> non_matches
[1] ".outcome" "special" "attent" "special_attent" "assault_and"
[6] "and_batteri" "ip" "drug_poss" "runaway" "i_p"
[11] "nuisanc" "investig_person" "traff_acc" "accident" "aggravated"
[16] "possession" "vehicle"


I also have a data frame.

For each value in my vector, I would like to create a new feature on my df with a value of zero.

Tried:

library(foreach)
foreach(i = seq_len(length(non_matches))) %do% {
pp_new_data$non_matches[i] <- 0
}


Also tried

library(foreach)
library(dplyr)
foreach(i = seq_len(length(non_matches))) %do% {
pp_new_data <- mutate(pp_new_data, non_matches[i] = 0)
}


In both cases I failed.

How can I do the following using a loop?

pp_new_data$.outcome <- 0
pp_new_data$special <- 0
pp_new_data$attent <- 0
etc.

Answer Source

mutate_at can modify a vector of column names. However, it applies a function, so we just create a function that always returns 0.

library('tidyverse')

pp_new_data <- tibble(dummy_data = c(1, 2, 3))
non_matches <- c('special', 'attent', 'special_attent', 'assault_and')

mutate_at(pp_new_data, non_matches, function(...) 0)
# # A tibble: 3 x 5
#   dummy_data special attent special_attent assault_and
#        <dbl>   <dbl>  <dbl>          <dbl>       <dbl>
# 1          1       0      0              0           0
# 2          2       0      0              0           0
# 3          3       0      0              0           0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download