How to read a string in one column and convert to a float value in a new colum?

Newbee question working on a class project...

I know I need to mutate the dataframe and create a new column of interest. How do I go about taking [a, b, c, d, e, e, c, b, a] for example (values limited 'a' through 'e') and convert them to a float a = 1.0, b = 2.0, etc.?

I have the parent dataframe that contains the initial dataset. If there is a new0user-friendly documentation set you can point me to that would be welcome also. Thanks in advance!


#example data in df 
(df <- tibble(myletters=c(letters[1:5],letters[4:1])))

# make a numeric representation
(df2 <- mutate(df,
               var_of_interest = as.numeric(forcats::as_factor(myletters))))

As a new user I either do not fully understand how to implement the solution you are providing, or I did not express the initial problem correctly.

The column in the existing data frame consists of a 5-level value factor type data. "Excellent", "Very good", "good", and "poor". I would like to either replace the values in the current column with numerical values 5, 4, 3, 2, 1 respectively, or create a new column with the numeric values present.

I think the simplest way is to first add as a column to the data frame and then use recode()

df$col <- [your string here]
recode(df$col, 1.0=a, 2.0=b, 3.0=c....) -> df

where "df" is the name of your data frame and "col" is the name of the column

If the column was already a part of the initial dataset, then just skip the first line

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.