Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

Add new columns to dataframe with colnames defined from a paste function using one variable [duplicate]

$
0
0

I want to add 4 new columns to a dataframe with their colnames defined from a paste function using one variable called but it doesn't work.

# Data sample :
Data = data.frame("Dummy"=rbind("0000006498","0000012926","0000020320","0000023283","0000023879"), stringsAsFactors=F)


# This works:
Stat = cbind.data.frame(Data, "Pre0"=NA, "Pre1"=NA, "PreA"=NA, "PreZE"=NA)

# Result:
#> Stat
#  Dummy       Pre0 Pre1 PreA  PreZE
#1 0000006498   NA   NA   NA    NA
#2 0000012926   NA   NA   NA    NA
#3 0000020320   NA   NA   NA    NA
#4 0000023283   NA   NA   NA    NA
#5 0000023879   NA   NA   NA    NA


# But I want do to the same result using a <Mod> variable to generate the column names like this:
Mod = c("0", "1", "A", "ZE")
Stat = cbind.data.frame(Data, noquote(paste0('"', paste(paste0('Pre' , Mod, '"=NA'), collapse=', "'))))

# It doesn't work and the result is:
#Error in data.frame(..., check.names = FALSE): 
#  les arguments impliquent des nombres de lignes différents : 5, 1

# Despite of the "noquote" part of code seems to work:
#> noquote(paste0('"', paste(paste0('Pre' , Mod, '"=NA'), collapse=', "')))
#[1] "Pre0"=NA, "Pre1"=NA, "PreA"=NA, "PreZE"=NA

Thank you in advance for your help.


Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>