I am a beginner with R and I have a vector called "condition" and it has following values, I want to change the value of condition to number of hours left for all the records.
condition <- c("10 days left", "3 days left", "22 hours left", "54 hours left", "10 minutes", "9 minutes", "Listing Expired")
Just to verify whether my logical concept is good, I first tried my logic on one element i.e. element[2] of the vector. It worked and I got my desired result
b <- as.numeric(word(condition[2]),1)*24
b
[1] 72
bc <- paste(b, gsub(".*days left.*", "hours left", condition[2]))
bc
"72 hours left"
I then tried to put it in for loop to apply the same logic on every element of vector. However it just worked for 1st two values but rest iterations are completely wrong. I am getting warnings too. Please help what changes do I need to make to get my desired output ??
Declaring a variable to get the 2nd element of my strings
var2nd <- word(condition,2)
var2nd
Now creating for loop to calculate hours left for every value in the vector condition
Hours_left <- for (var in condition) {
if (var2nd == "days") {
b = as.numeric(word(var,1))*24
c = paste(b, gsub(".*days left.*", "hours left", var))
print(c)
} else if ( var2nd == "minutes") {
d <- round(as.numeric(word(var, 1)/60, digits = 2))
e <- as.character(paste(d, gsub(".*minutes.*", "hours left", var)))
print(e)
} else if (var2nd == "Expired") {
print(var)
} else if (var2nd == "hours") {
print(var)
}
}
[1] "240 hours left"
[1] "72 hours left"
[1] "528 22 hours left"
[1] "1296 54 hours left"
[1] "240 10 minutes"
[1] "216 9 minutes"
[1] "NA Listing Expired"
Warning messages:
1: In if (var2nd == "days") { :
the condition has length > 1 and only the first element will be used
2: In if (var2nd == "days") { :
the condition has length > 1 and only the first element will be used
3: In if (var2nd == "days") { :
the condition has length > 1 and only the first element will be used
4: In if (var2nd == "days") { :
the condition has length > 1 and only the first element will be used
5: In if (var2nd == "days") { :
the condition has length > 1 and only the first element will be used
6: In if (var2nd == "days") { :
the condition has length > 1 and only the first element will be used
7: In if (var2nd == "days") { :
the condition has length > 1 and only the first element will be used
8: NAs introduced by coercion