2
I am writing an R script to convert data that is in text files with fixed width fields for CSV files.
It happens that in addition to the transformation I do some "formatting" in the data and has a column with the recipe code that can assume two format types, according to the first character of each string:
If the first character is "9", the format is 9.0.0.0.00.0.0.00.00.00.00, otherwise it will be 0.0.0.0.00.00.00.00
Data is stored in a data frame df
and the field to be formatted is the codigo_receita
.
I tried that, but it’s obviously not working:
if(startsWith(df$codigo_receita, "9")){
df$codigo_receita <- sprintf(
"%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s",
str_sub(df$codigo_receita, start = 1, end = 1),
str_sub(df$codigo_receita, start = 2, end = 2),
str_sub(df$codigo_receita, start = 3, end = 3),
str_sub(df$codigo_receita, start = 4, end = 4),
str_sub(df$codigo_receita, start = 5, end = 5),
str_sub(df$codigo_receita, start = 6, end = 7),
str_sub(df$codigo_receita, start = 8, end = 8),
str_sub(df$codigo_receita, start = 9, end = 9),
str_sub(df$codigo_receita, start = 10, end = 11),
str_sub(df$codigo_receita, start = 12, end = 13),
str_sub(df$codigo_receita, start = 15, end = 15)
)
}else{
df$codigo_receita <- sprintf(
"%s.%s.%s.%s.%s.%s.%s.%s.%s.%s",
str_sub(df$codigo_receita, start = 1, end = 1),
str_sub(df$codigo_receita, start = 2, end = 2),
str_sub(df$codigo_receita, start = 3, end = 3),
str_sub(df$codigo_receita, start = 4, end = 4),
str_sub(df$codigo_receita, start = 5, end = 6),
str_sub(df$codigo_receita, start = 7, end = 7),
str_sub(df$codigo_receita, start = 8, end = 8),
str_sub(df$codigo_receita, start = 9, end = 10),
str_sub(df$codigo_receita, start = 11, end = 12),
str_sub(df$codigo_receita, start = 13, end = 14)
)
}
Can you give an example of two codes before and after formatting? I think it’s easier to suggest something having them to base on
– Jorge Mendes
And changing the if/Else to the ifelse function can be a place to start. if/Else only work for one element, they don’t look at an entire vector. The difference is yes
– Jorge Mendes