I occasionally want to export a dataset to Stata but I sometimes have variable names that exceed the 32 character limit that Stata allows, so I am trying to write a function that identifies those variables and then truncates them to 32 characters. The below code works in everything (i.e. displaying offending variable indices and names) except actually writing the truncated names back to the data frame.
short_var_names <- function(data.in){
long_names_indices <- data.frame(long_name_indices = which(nchar(names(data.in)) > 32))
long_names <- data.frame(long_names = names(data.in[which(nchar(names(data.in)) > 32)]))
short_names <- data.frame(short_names = names(data.in[as.numeric(unlist(long_names_indices))]))
print(long_names_indices)
print(long_names)
print(short_names)
names(data.in) <- substring(names(data.in), 1, 32) # now do the actual operation on the df
}
short_var_names(dat_clin)
When I use the following outside of the function, it works as expected:
names(dat_clin) <- substring(names(dat_clin), 1, 32)
So, why isn't this command being returned in the function?