简体   繁体   中英

Replace values in String with matching values from another

I am given the following:

text <- c("RREPLACE EACH WITH NUMBER FROM LETTERFREQ")

and the given:

lf <- 1 / 100 * c(
  A = 6.756, B = 1.234, C = 2.302, D = 3.518, E = 10.508, F = 1.843, G = 1.667,
  H = 5.041, I = 5.763, J = 0.127, K = 0.639, L = 3.330, M = 1.990, N = 5.583,
  O = 6.210, P = 1.596, Q = 0.079, R = 4.953, S = 5.234, T = 7.492, U = 2.282,
  V = 0.809, W = 1.952, X = 0.124, Y = 1.633, Z = 0.061, ` ` = 17.272)

My goal is to replace each letter in text with a number matching the numeric values from lf so that I can calculate the sum.

I created a plaintext:

plainte <- strsplit(text, "")[[1]]

But I am lost from here on. How do I match each letter in text with the corresponding numeric value?

You can use match for that:

lf[match(plainte, names(lf))]

To calculate the sum:

sum(lf[match(plainte, names(lf))])

which gives:

[1] 2.79333

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