Home > front end >  How to convert string to number in R
How to convert string to number in R

Time:05-13

I have a dataset like this:

name <- c("a1", "c8", "c8", "ds 14m", "ms 34k", "ds 14m")
num <- c(3, 5, 6, 2, 8, 4)

df <- cbind(name, num)
df <- as.data.frame(df)

I want a dataset like this:

name2 <- c("1", "2", "2", "3", "4", "3")
df2 <- cbind(name2, num)
df2 <- as.data.frame(df2)

Is there a function to do the transformation of the column name automatically?

CodePudding user response:

Using match.

tmp=unique(df$name)
names(tmp)=1:length(tmp)
match(df$name,tmp)
[1] 1 2 2 3 4 3

Using factor.

as.character(factor(df$name,labels=1:length(unique(df$name))))
[1] "1" "2" "2" "3" "4" "3"

CodePudding user response:

Coerce as.factor and strip off levels, i.e. as.integer.

transform(df, name=as.integer(as.factor(name)))
#   name num
# 1    1   3
# 2    2   5
# 3    2   6
# 4    3   2
# 5    4   8
# 6    3   4
  •  Tags:  
  • r
  • Related