Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a z.fill function in R

Tags:

python

r

width

fill

I have a data frame

df=data.frame(f=c('a','ab','abc'),v=1:3)

and make a new column with:

df$c=paste(df$v,df$f,sep='')

the result is

> df
    f v    c
1   a 1   1a
2  ab 2  2ab
3 abc 3 3abc

I would like column c to be in this format:

> df
    f v    c
1   a 1 1  a
2  ab 2 2 ab
3 abc 3 3abc

such that the total length of the concatenated values is a fixed number (in this case 4 characters) and to fill it will a chosen character, such as | (in this case \w).

Is there a function like this in R? I think it is similar to the z.fill function in python, but I am not a python programmer, and would prefer to stay in R as opposed to switching between languages for processing. Ultimately, I am creating a supervariable of 10 columns, and think this would help in downstream processing

I guess it would be in the paste function, but not sure how to 'fill a factor' so that it is of a fixed width

like image 273
frank Avatar asked Mar 12 '23 06:03

frank


2 Answers

You can use the format() function to pretty print the values of your column. For example:

> format(df$f, width = 3, justify = "right")
[1] "  a" " ab" "abc"

So your code should be:

df <- within(df, {
  c <- paste0(v, format(f, width = 3, justify = "right"))
})
df

The result:

> df
    f v    c
1   a 1 1  a
2  ab 2 2 ab
3 abc 3 3abc
like image 70
Andrie Avatar answered Mar 19 '23 12:03

Andrie


You can use the formatCfunction as follow

df$c <- paste(df$v, formatC(as.character(df$f), width = 3, flag = " "), sep = "")

df
    f v    c
1   a 1 1  a
2  ab 2 2 ab
3 abc 3 3abc

DATA

df <- data.frame(f = c('a','ab','abc'), v=1:3)
like image 34
Claudio Fronterrè Avatar answered Mar 19 '23 12:03

Claudio Fronterrè