在数据框中重复列,但用给定数量的零替换空格

时间:2015-06-22 09:46:36

标签: r

我有一个包含多个列的数据框(df)。 A列包含格式为“1 34”,“368 879”的值,......因此中间有空格。 我想创建一个新列,用固定数量0替换空格。我的意思是:

      A     Rep     New_A
1     15    3       100015  
378   567   2       37800567
45    2     4       4500002

对于单个值,例如df [1,“A”],这样的工作原理:

New_A <- gsub("[[:punct:]])|\\s+",paste(rep(0,df[1,"Rep"]), sep="", collapse=""), df[1,"A"])

但对于整个数据帧,我尝试过,但它不起作用:

df$New_A <- gsub("[[:punct:]])|\\s+",paste(rep(0,df$Rep), sep="", collapse=""), df$A])

我可以用for循环来做,但我宁愿避免这种情况,因为我的数据帧有超过1000000行...所以它根本没有效率......

1 个答案:

答案 0 :(得分:0)

按照@CathG的想法,这就是我得到的要求:

df$New_A <- mapply(function(x,y){gsub("[[:punct:]])|\\s+",paste(rep(0,y), sep="", collapse=""), x)}, x=df$A, y=df$Rep)

其中:

rep(0,y) #produces as much 0 as indicated in df$Rep --> gives a vector of 0

paste(rep(0,y), sep="", collapse="") #puts all zeros of the vector together (like "000")

gsub("[[:punct:]])|\\s+",...,...) #substitutes the white spaces of df$A by the "string of zeros"