Peter Chung Peter Chung - 22 days ago 21
R Question

R change strings into numeric in a data frame

I have a data frame as below and would like to generate another data frame by replacing the characters in the dataframe into numeric according condition.

condition:
GD 5
O 4.5
AV 3
B 2.5

dataframe:
Name Peter Paul Mary Chan Jose
Nokia B O O GD GD
iPhone AV O O O O
Moto AV AV O O AV
HTC B O AV AV AV

dput:
structure(list(Name = c("Nokia", "iPhone", "Moto", "HTC"), Peter =
c("B", "AV", "AV", "B"), Paul = c("O", "O", "AV", "O"), Mary =
c("O", "O", "O", "AV"), Chan = c("GD", "O", "O", "AV"), Jose =
c("GD", "O", "AV", "AV")), .Names =
c("Name", "Peter", "Paul", "Mary", "Chan", "Jose"), class = "data.frame", row.names = c(NA, -4L))

desired output:
Name Peter Paul Mary Chan Jose
Nokia 2.5 4.5 4.5 5 5
iPhone 3 4.5 4.5 4.5 4.5
Moto 3 3 4.5 4.5 3
HTC 2.5 4.5 3 3 3


Thanks for your help!!!

Answer

One option is using match by looping through the columns

df1[-1] <- lapply(df1[-1], function(x) keyval$v2[match(x, keyval$v1)])
df1
#    Name Peter Paul Mary Chan Jose
#1  Nokia   2.5  4.5  4.5  5.0  5.0
#2 iPhone   3.0  4.5  4.5  4.5  4.5
#3   Moto   3.0  3.0  4.5  4.5  3.0
#4    HTC   2.5  4.5  3.0  3.0  3.0

where 'keyval' is a 'data.frame' with 'v1' and 'v2' as the 'key' and 'value' columns.

Comments