简体   繁体   中英

Replacing text in data frame in r

I want to replace text in one column with numbers

for example,

>df = chickwts
>df
   weight      feed
1     179 horsebean
2     160 horsebean
3     136 horsebean
4     227 horsebean
5     217 horsebean
6     168 horsebean
7     108 horsebean
8     124 horsebean
9     143 horsebean
10    140 horsebean
11    309   linseed
12    229   linseed
...

How do I replace all 6 feed names with the numbers 1:6 in one command?

I am a beginner in r and spent an hour trying different functions with no success. I want to use

fr = unique(df$feed)
to = 1:6

But beyond that, I am having difficulty.

Depends what you want to do. If you are planning on doing some statistical analysis that treats feed as a categorical variable then as.factor is what you are looking for. Try this:

#  Turn them into a factor like this
df$feed <- as.factor( df$feed )

#  Here are the levels of the factor
levels( df$feed )
# [1] "horsebean" "linseed" 

#  If you want their underlying numerical values
as.numeric( df$feed )
# [1] 1 1 1 1 1 1 1 1 1 1 2 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM