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
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
You can use the formatC
function 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With