I’m having trouble with what I think is a basic R task.
Here’s my sample dataframe named ‘b’
Winner Color Size
Tom Yellow Med
Jerry Yellow Lar
Jane Blue Med
where items in the Winner column are factors.
I’m trying to change “Tom” in the dataframe to “Tom LLC” and I can’t get it done.
Here’s what I tried:
Simple way:
b$winner[b$winner=='Tom'] = as.factor('Tom LLC')
but that failed with “invalid factor level, NAs generated”
Next I tried a more advanced route:
name_reset = function (x, y, z) {
if (x$winner == y) {x$winner = z}
}
b = adply(b,1,name_reset,'Tom','Tom LLC')
but that failed with “Error in list_to_dataframe(res, attr(.data, “split_labels”)) :
Results are not equal lengths”
I feel I’m missing something basic. Can someone redirect me or offer suggestions on the code I wrote above? Thank you very much
What you want to do is change the values via levels. Levels gives you access to the labels in a factor. Calling it on a factor shows the labels, and assigning to the levels function overwrites the labels for the factor.
Once you start working with the levels function you can change the values however you want. I think gsub is probably the easiest.
Try this:
-mcpeterson