I would like to transform certain columns with a specific string code to a factor in the same data.frame. However, I am stymied by the initial task of passing the data.frame column reference to my function. Working from examples here and its linked pages, I believe the following should work:
#feed string to function
set.seed(42)
df <- data.frame(
chr1 = sample(letters[1:4], 10, T),
chr2 = sample(letters[4:7], 10, T),
stringsAsFactors = F
)
tofactor <- function(dat,column) {
dat[,column] <- as.factor(dat[,column])
}
tofactor(df, "chr1")
typeof(df$chr1)
However, the result of this operation is persistence of string encoding for df$chr1
. I have also tried a reference using a double square brackets approach without success.
Thanks for your assistance.