Changing characters in R (Google Trends Data)

60 Views Asked by At

I have been recently using Google Trends data, and have come across non-integer values which cause the values to become characters. That is no issue since you can convert them in integers later. However, there are certain characters such as "<1" or "<Â 1" which I need to change into 0's. My idea was to first change these characters into 0's and then use as.integer to convert all the values at once. That worked with the following code:

i=1
for (i in 1:nrow(result)) {
result[[i]]$hits[result[[i]]$hits=="<1"] <- "0"
}

However, when I went to compute the same loop for the "<Â 1" values, nothing changes. I don't know if this might be because it has a special character or anything of that nature, but I can't get the loop to change the values.

i=1
for (i in 1:nrow(result)) {
  result[[i]]$hits[result[[i]]$hits=="<Â 1"] <- "0"
}

Vañues after I apply the loops

As explained above, I then change all the values to integers in order to compute, so I would need all of the "<Â 1" to be 0's.

2

There are 2 best solutions below

0
On

It would be enough to slightly modify the as.integer function:

sample_string <- c("1", "A", "3", "B")
to_int_or_zero <- function(x) {
  res <- as.integer(x)
  ifelse(is.na(res), 0, res)
}

to_int_or_zero(sample_string)

For future please consider providing a sample object generated by dput or manually as it would make it easier to provide the solution. In the context of your object you will be looking to apply your function to the vector representing the elements, so likely this will be to_int_or_zero(<your hits object hits>). You can use the apply family to iterate over multiple hits object or continue with your list.

0
On

change the values to numeric ; the characters which cant be converted will be changed to NA.; Change all the NA's to 0.