0

How could I change string values to any numeric value, as long as each unique string has a unique numeric return.

for example INTcntry gets a value 1 for 2708BG, 2 for 2703BG... However I don't want to assign it manually, because I have 9000 somewhat different string values.

     idno       INTcntry
4039 3857         2708BG
4040 3858         2708BG
4041 3862         2704BG
4042 3863         2704BG
4043 3864         2704BG
4044 3865         2704BG
4045 3867         2704BG
4046 3868         2704BG
4047 3871         2703BG
4048 3872         2703BG
4199  161         1011CH
4201  163         1011CH

2 Answers 2

2

I suspect that INTcntry is a factor,

is.factor(dd$INTcntry)

in which case, just exploit that fact:

R> levels(dd$INTcntry)
[1] "1011CH" "2703BG" "2704BG" "2708BG"
R> labels(dd$INTcntry)
[1] "1" "2" "3" "4" "5" "6" "7" "8"

so just convert the labels to numeric values:

as.numeric(labels(dd$INTcntry))

or

as.numeric(dd$INTcntry)

If INTcntry isn't a factor, then just use:

factor(dd$INTcntry)
Sign up to request clarification or add additional context in comments.

Comments

1

One way is to convert your variable to a factor and then use as.numeric :

as.numeric(factor(df$INTcntry))

2 Comments

Of course, the question then is, why you need the numeric and cannot just work with the factor.
That is true, I want to use this data within another program and just wanted to make sure it can read the values properly. But maybe it can read the string values just as good. Will try.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.