0

I'm working with a dataframe and two character vectors. I would like to replace all the elements of a column, given the assignment "rule" given by the character vectors. For example:

dat <- cbind(c("Zone 1A", "Zone 1C","Zone 2B ","Zone 2C"), 1:4)
#assignment rules
vec1 <- c("Zone 1A","Zone 1B ","Zone 1C","Zone 2A","Zone 2B","Zone 2C") 
vec2 <- c("Zone 1","Zone 1","Zone 1","Zone 2","Zone 2","Zone 2")

This means that everytime I see an element of vec1 I replace it with the element of vec2 of the same index. So everytime I get "Zone 1B" y replace it with "Zone 1". I would like do have dat with its first column replaced using the assignment rule.

Note that vec1 and vec2 have the same length and dat randomly take values found in vec1.

Alvaro Acedo
  • 23
  • 1
  • 5
  • You can use a named vector to match and replace `dat[[1]] <- setNames(vec2, vec1)[trimws(dat[[1]])]`. ASsuming that data.frame is created as `dat <- data.frame(col1 = ..., col2 = 1:4)` – akrun Jul 01 '20 at 23:25
  • See previous answers here, e.g.: https://stackoverflow.com/questions/3905038/replace-values-in-a-vector-based-on-another-vector and https://stackoverflow.com/questions/18456968/how-do-i-map-a-vector-of-values-to-another-vector-with-my-own-custom-map-in-r/18457055 which I think cover your query. – thelatemail Jul 01 '20 at 23:45

2 Answers2

1

I think you may use this,I comment it for u.

dataframe as data = data.frame(dat)

    while (nrow(data) <= length(vec1)-1){ #Here u put the assigment u want e.g vec1
    data[nrow(data)+1,] = (numeric(length(vec1)))
     }

    data[,1] <- vec1 #Here you put the assigment you want 
0

You could create a lookup dataframe with vec1 and vec2 as columns. Note that, there were some whitespaces in the data that your shared which I have removed.

dat <- data.frame(a = c("Zone 1A", "Zone 1C","Zone 2B","Zone 3C"), b = 1:4)
vec1 <- c("Zone 1A","Zone 1B","Zone 1C","Zone 2A","Zone 2B","Zone 2C") 
vec2 <- c("Zone 1","Zone 1","Zone 1","Zone 2","Zone 2","Zone 2")
lookup <- data.frame(vec1, vec2)

You can use match to replace values.

dat$a <- lookup$vec2[match(dat$a, lookup$vec1)]

Based on the data shared we can remove the last character in a column which returns us the proper "Zone" value. You can use sub to do that.

dat$a <- sub('[A-Z]$', '', dat$a)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213